Expanding documentation for first ~500 lines or so
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @file
5 */
6
7 /**
8 * Class representing a MediaWiki article and history.
9 *
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
13 *
14 */
15 class Article {
16 /**@{{
17 * @private
18 */
19 var $mComment = ''; // !<
20 var $mContent; // !<
21 var $mContentLoaded = false; // !<
22 var $mCounter = -1; // !< Not loaded
23 var $mCurID = -1; // !< Not loaded
24 var $mDataLoaded = false; // !<
25 var $mForUpdate = false; // !<
26 var $mGoodAdjustment = 0; // !<
27 var $mIsRedirect = false; // !<
28 var $mLatest = false; // !<
29 var $mMinorEdit; // !<
30 var $mOldId; // !<
31 var $mPreparedEdit = false; // !< Title object if set
32 var $mRedirectedFrom = null; // !< Title object if set
33 var $mRedirectTarget = null; // !< Title object if set
34 var $mRedirectUrl = false; // !<
35 var $mRevIdFetched = 0; // !<
36 var $mRevision; // !<
37 var $mTimestamp = ''; // !<
38 var $mTitle; // !<
39 var $mTotalAdjustment = 0; // !<
40 var $mTouched = '19700101000000'; // !<
41 var $mUser = -1; // !< Not loaded
42 var $mUserText = ''; // !<
43 var $mParserOptions; // !<
44 var $mParserOutput; // !<
45 /**@}}*/
46
47 /**
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
51 */
52 public function __construct( Title $title, $oldId = null ) {
53 $this->mTitle =& $title;
54 $this->mOldId = $oldId;
55 }
56
57 /**
58 * Constructor from an article article
59 * @param $id The article ID to load
60 */
61 public static function newFromID( $id ) {
62 $t = Title::newFromID( $id );
63 # FIXME: doesn't inherit right
64 return $t == null ? null : new self( $t );
65 # return $t == null ? null : new static( $t ); // PHP 5.3
66 }
67
68 /**
69 * Tell the page view functions that this view was redirected
70 * from another page on the wiki.
71 * @param $from Title object.
72 */
73 public function setRedirectedFrom( Title $from ) {
74 $this->mRedirectedFrom = $from;
75 }
76
77 /**
78 * If this page is a redirect, get its target
79 *
80 * The target will be fetched from the redirect table if possible.
81 * If this page doesn't have an entry there, call insertRedirect()
82 * @return mixed Title object, or null if this page is not a redirect
83 */
84 public function getRedirectTarget() {
85 if ( !$this->mTitle || !$this->mTitle->isRedirect() )
86 return null;
87 if ( !is_null( $this->mRedirectTarget ) )
88 return $this->mRedirectTarget;
89 # Query the redirect table
90 $dbr = wfGetDB( DB_SLAVE );
91 $row = $dbr->selectRow( 'redirect',
92 array( 'rd_namespace', 'rd_title' ),
93 array( 'rd_from' => $this->getID() ),
94 __METHOD__
95 );
96 if ( $row ) {
97 return $this->mRedirectTarget = Title::makeTitle( $row->rd_namespace, $row->rd_title );
98 }
99 # This page doesn't have an entry in the redirect table
100 return $this->mRedirectTarget = $this->insertRedirect();
101 }
102
103 /**
104 * Insert an entry for this page into the redirect table.
105 *
106 * Don't call this function directly unless you know what you're doing.
107 * @return Title object
108 */
109 public function insertRedirect() {
110 $retval = Title::newFromRedirect( $this->getContent() );
111 if ( !$retval ) {
112 return null;
113 }
114 $dbw = wfGetDB( DB_MASTER );
115 $dbw->replace( 'redirect', array( 'rd_from' ),
116 array(
117 'rd_from' => $this->getID(),
118 'rd_namespace' => $retval->getNamespace(),
119 'rd_title' => $retval->getDBkey()
120 ),
121 __METHOD__
122 );
123 return $retval;
124 }
125
126 /**
127 * Get the Title object this page redirects to
128 *
129 * @return mixed false, Title of in-wiki target, or string with URL
130 */
131 public function followRedirect() {
132 $text = $this->getContent();
133 return $this->followRedirectText( $text );
134 }
135
136 /**
137 * Get the Title object this text redirects to
138 *
139 * @param $text string article content containing redirect info
140 * @return mixed false, Title of in-wiki target, or string with URL
141 */
142 public function followRedirectText( $text ) {
143 $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
144 # process if title object is valid and not special:userlogout
145 if ( $rt ) {
146 if ( $rt->getInterwiki() != '' ) {
147 if ( $rt->isLocal() ) {
148 // Offsite wikis need an HTTP redirect.
149 //
150 // This can be hard to reverse and may produce loops,
151 // so they may be disabled in the site configuration.
152 $source = $this->mTitle->getFullURL( 'redirect=no' );
153 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
154 }
155 } else {
156 if ( $rt->getNamespace() == NS_SPECIAL ) {
157 // Gotta handle redirects to special pages differently:
158 // Fill the HTTP response "Location" header and ignore
159 // the rest of the page we're on.
160 //
161 // This can be hard to reverse, so they may be disabled.
162 if ( $rt->isSpecial( 'Userlogout' ) ) {
163 // rolleyes
164 } else {
165 return $rt->getFullURL();
166 }
167 }
168 return $rt;
169 }
170 }
171 // No or invalid redirect
172 return false;
173 }
174
175 /**
176 * get the title object of the article
177 * @return Title object of current title
178 */
179 public function getTitle() {
180 return $this->mTitle;
181 }
182
183 /**
184 * Clear the object
185 * @private
186 */
187 public function clear() {
188 $this->mDataLoaded = false;
189 $this->mContentLoaded = false;
190
191 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
192 $this->mRedirectedFrom = null; # Title object if set
193 $this->mRedirectTarget = null; # Title object if set
194 $this->mUserText =
195 $this->mTimestamp = $this->mComment = '';
196 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
197 $this->mTouched = '19700101000000';
198 $this->mForUpdate = false;
199 $this->mIsRedirect = false;
200 $this->mRevIdFetched = 0;
201 $this->mRedirectUrl = false;
202 $this->mLatest = false;
203 $this->mPreparedEdit = false;
204 }
205
206 /**
207 * Note that getContent/loadContent do not follow redirects anymore.
208 * If you need to fetch redirectable content easily, try
209 * the shortcut in Article::followContent()
210 *
211 * @return Return the text of this revision
212 */
213 public function getContent() {
214 global $wgUser, $wgContLang, $wgOut, $wgMessageCache;
215 wfProfileIn( __METHOD__ );
216 if ( $this->getID() === 0 ) {
217 # If this is a MediaWiki:x message, then load the messages
218 # and return the message value for x.
219 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
220 # If this is a system message, get the default text.
221 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle->getText() ) );
222 $wgMessageCache->loadAllMessages( $lang );
223 $text = wfMsgGetKey( $message, false, $lang, false );
224 if ( wfEmptyMsg( $message, $text ) )
225 $text = '';
226 } else {
227 $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
228 }
229 wfProfileOut( __METHOD__ );
230 return $text;
231 } else {
232 $this->loadContent();
233 wfProfileOut( __METHOD__ );
234 return $this->mContent;
235 }
236 }
237
238 /**
239 * Get the text of the current revision. No side-effects...
240 *
241 * @return Return the text of the current revision
242 */
243 public function getRawText() {
244 // Check process cache for current revision
245 if ( $this->mContentLoaded && $this->mOldId == 0 ) {
246 return $this->mContent;
247 }
248 $rev = Revision::newFromTitle( $this->mTitle );
249 $text = $rev ? $rev->getRawText() : false;
250 return $text;
251 }
252
253 /**
254 * This function returns the text of a section, specified by a number ($section).
255 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
256 * the first section before any such heading (section 0).
257 *
258 * If a section contains subsections, these are also returned.
259 *
260 * @param $text String: text to look in
261 * @param $section Integer: section number
262 * @return string text of the requested section
263 * @deprecated
264 */
265 public function getSection( $text, $section ) {
266 global $wgParser;
267 return $wgParser->getSection( $text, $section );
268 }
269
270 /**
271 * Get the text that needs to be saved in order to undo all revisions
272 * between $undo and $undoafter. Revisions must belong to the same page,
273 * must exist and must not be deleted
274 * @param $undo Revision
275 * @param $undoafter Revision Must be an earlier revision than $undo
276 * @return mixed string on success, false on failure
277 */
278 public function getUndoText( Revision $undo, Revision $undoafter = null ) {
279 $undo_text = $undo->getText();
280 $undoafter_text = $undoafter->getText();
281 $cur_text = $this->getContent();
282 if ( $cur_text == $undo_text ) {
283 # No use doing a merge if it's just a straight revert.
284 return $undoafter_text;
285 }
286 $undone_text = '';
287 if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
288 return false;
289 return $undone_text;
290 }
291
292 /**
293 * @return int The oldid of the article that is to be shown, 0 for the
294 * current revision
295 */
296 public function getOldID() {
297 if ( is_null( $this->mOldId ) ) {
298 $this->mOldId = $this->getOldIDFromRequest();
299 }
300 return $this->mOldId;
301 }
302
303 /**
304 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
305 *
306 * @return int The old id for the request
307 */
308 public function getOldIDFromRequest() {
309 global $wgRequest;
310 $this->mRedirectUrl = false;
311 $oldid = $wgRequest->getVal( 'oldid' );
312 if ( isset( $oldid ) ) {
313 $oldid = intval( $oldid );
314 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
315 $nextid = $this->mTitle->getNextRevisionID( $oldid );
316 if ( $nextid ) {
317 $oldid = $nextid;
318 } else {
319 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
320 }
321 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
322 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
323 if ( $previd ) {
324 $oldid = $previd;
325 }
326 }
327 }
328 if ( !$oldid ) {
329 $oldid = 0;
330 }
331 return $oldid;
332 }
333
334 /**
335 * Load the revision (including text) into this object
336 */
337 function loadContent() {
338 if ( $this->mContentLoaded ) return;
339 wfProfileIn( __METHOD__ );
340 # Query variables :P
341 $oldid = $this->getOldID();
342 # Pre-fill content with error message so that if something
343 # fails we'll have something telling us what we intended.
344 $this->mOldId = $oldid;
345 $this->fetchContent( $oldid );
346 wfProfileOut( __METHOD__ );
347 }
348
349
350 /**
351 * Fetch a page record with the given conditions
352 * @param $dbr Database object
353 * @param $conditions Array
354 * @return mixed Database result resource, or false on failure
355 */
356 protected function pageData( $dbr, $conditions ) {
357 $fields = array(
358 'page_id',
359 'page_namespace',
360 'page_title',
361 'page_restrictions',
362 'page_counter',
363 'page_is_redirect',
364 'page_is_new',
365 'page_random',
366 'page_touched',
367 'page_latest',
368 'page_len',
369 );
370 wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
371 $row = $dbr->selectRow(
372 'page',
373 $fields,
374 $conditions,
375 __METHOD__
376 );
377 wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
378 return $row ;
379 }
380
381 /**
382 * Fetch a page record matching the Title object's namespace and title
383 * using a sanitized title string
384 *
385 * @param $dbr Database object
386 * @param $title Title object
387 * @return mixed Database result resource, or false on failure
388 */
389 public function pageDataFromTitle( $dbr, $title ) {
390 return $this->pageData( $dbr, array(
391 'page_namespace' => $title->getNamespace(),
392 'page_title' => $title->getDBkey() ) );
393 }
394
395 /**
396 * Fetch a page record matching the requested ID
397 *
398 * @param $dbr Database
399 * @param $id Integer
400 */
401 protected function pageDataFromId( $dbr, $id ) {
402 return $this->pageData( $dbr, array( 'page_id' => $id ) );
403 }
404
405 /**
406 * Set the general counter, title etc data loaded from
407 * some source.
408 *
409 * @param $data Database row object or "fromdb"
410 */
411 public function loadPageData( $data = 'fromdb' ) {
412 if ( $data === 'fromdb' ) {
413 $dbr = wfGetDB( DB_MASTER );
414 $data = $this->pageDataFromId( $dbr, $this->getId() );
415 }
416
417 $lc = LinkCache::singleton();
418 if ( $data ) {
419 $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
420
421 $this->mTitle->mArticleID = intval( $data->page_id );
422
423 # Old-fashioned restrictions
424 $this->mTitle->loadRestrictions( $data->page_restrictions );
425
426 $this->mCounter = intval( $data->page_counter );
427 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
428 $this->mIsRedirect = intval( $data->page_is_redirect );
429 $this->mLatest = intval( $data->page_latest );
430 } else {
431 if ( is_object( $this->mTitle ) ) {
432 $lc->addBadLinkObj( $this->mTitle );
433 }
434 $this->mTitle->mArticleID = 0;
435 }
436
437 $this->mDataLoaded = true;
438 }
439
440 /**
441 * Get text of an article from database
442 * Does *NOT* follow redirects.
443 *
444 * @param $oldid Int: 0 for whatever the latest revision is
445 * @return mixed string containing article contents, or false if null
446 */
447 function fetchContent( $oldid = 0 ) {
448 if ( $this->mContentLoaded ) {
449 return $this->mContent;
450 }
451
452 $dbr = wfGetDB( DB_MASTER );
453
454 # Pre-fill content with error message so that if something
455 # fails we'll have something telling us what we intended.
456 $t = $this->mTitle->getPrefixedText();
457 $d = $oldid ? wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid ) : '';
458 $this->mContent = wfMsgNoTrans( 'missing-article', $t, $d ) ;
459
460 if ( $oldid ) {
461 $revision = Revision::newFromId( $oldid );
462 if ( is_null( $revision ) ) {
463 wfDebug( __METHOD__ . " failed to retrieve specified revision, id $oldid\n" );
464 return false;
465 }
466 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
467 if ( !$data ) {
468 wfDebug( __METHOD__ . " failed to get page data linked to revision id $oldid\n" );
469 return false;
470 }
471 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
472 $this->loadPageData( $data );
473 } else {
474 if ( !$this->mDataLoaded ) {
475 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
476 if ( !$data ) {
477 wfDebug( __METHOD__ . " failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
478 return false;
479 }
480 $this->loadPageData( $data );
481 }
482 $revision = Revision::newFromId( $this->mLatest );
483 if ( is_null( $revision ) ) {
484 wfDebug( __METHOD__ . " failed to retrieve current page, rev_id {$this->mLatest}\n" );
485 return false;
486 }
487 }
488
489 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
490 // We should instead work with the Revision object when we need it...
491 $this->mContent = $revision->getText( Revision::FOR_THIS_USER ); // Loads if user is allowed
492
493 $this->mUser = $revision->getUser();
494 $this->mUserText = $revision->getUserText();
495 $this->mComment = $revision->getComment();
496 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
497
498 $this->mRevIdFetched = $revision->getId();
499 $this->mContentLoaded = true;
500 $this->mRevision =& $revision;
501
502 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
503
504 return $this->mContent;
505 }
506
507 /**
508 * Read/write accessor to select FOR UPDATE
509 *
510 * @param $x Mixed: FIXME
511 * @return
512 */
513 public function forUpdate( $x = null ) {
514 return wfSetVar( $this->mForUpdate, $x );
515 }
516
517 /**
518 * Get the database which should be used for reads
519 *
520 * @return Database
521 * @deprecated - just call wfGetDB( DB_MASTER ) instead
522 */
523 function getDB() {
524 wfDeprecated( __METHOD__ );
525 return wfGetDB( DB_MASTER );
526 }
527
528 /**
529 * Get options for all SELECT statements
530 *
531 * @param $options Array: an optional options array which'll be appended to
532 * the default
533 * @return Array: options
534 */
535 protected function getSelectOptions( $options = '' ) {
536 if ( $this->mForUpdate ) {
537 if ( is_array( $options ) ) {
538 $options[] = 'FOR UPDATE';
539 } else {
540 $options = 'FOR UPDATE';
541 }
542 }
543 return $options;
544 }
545
546 /**
547 * @return int Page ID
548 */
549 public function getID() {
550 if ( $this->mTitle ) {
551 return $this->mTitle->getArticleID();
552 } else {
553 return 0;
554 }
555 }
556
557 /**
558 * @return bool Whether or not the page exists in the database
559 */
560 public function exists() {
561 return $this->getId() > 0;
562 }
563
564 /**
565 * Check if this page is something we're going to be showing
566 * some sort of sensible content for. If we return false, page
567 * views (plain action=view) will return an HTTP 404 response,
568 * so spiders and robots can know they're following a bad link.
569 *
570 * @return bool
571 */
572 public function hasViewableContent() {
573 return $this->exists() || $this->mTitle->isAlwaysKnown();
574 }
575
576 /**
577 * @return int The view count for the page
578 */
579 public function getCount() {
580 if ( -1 == $this->mCounter ) {
581 $id = $this->getID();
582 if ( $id == 0 ) {
583 $this->mCounter = 0;
584 } else {
585 $dbr = wfGetDB( DB_SLAVE );
586 $this->mCounter = $dbr->selectField( 'page',
587 'page_counter',
588 array( 'page_id' => $id ),
589 __METHOD__,
590 $this->getSelectOptions()
591 );
592 }
593 }
594 return $this->mCounter;
595 }
596
597 /**
598 * Determine whether a page would be suitable for being counted as an
599 * article in the site_stats table based on the title & its content
600 *
601 * @param $text String: text to analyze
602 * @return bool
603 */
604 public function isCountable( $text ) {
605 global $wgUseCommaCount;
606
607 $token = $wgUseCommaCount ? ',' : '[[';
608 return $this->mTitle->isContentPage() && !$this->isRedirect( $text ) && in_string( $token, $text );
609 }
610
611 /**
612 * Tests if the article text represents a redirect
613 *
614 * @param $text String: FIXME
615 * @return bool
616 */
617 public function isRedirect( $text = false ) {
618 if ( $text === false ) {
619 if ( $this->mDataLoaded ) {
620 return $this->mIsRedirect;
621 }
622 // Apparently loadPageData was never called
623 $this->loadContent();
624 $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
625 } else {
626 $titleObj = Title::newFromRedirect( $text );
627 }
628 return $titleObj !== null;
629 }
630
631 /**
632 * Returns true if the currently-referenced revision is the current edit
633 * to this page (and it exists).
634 * @return bool
635 */
636 public function isCurrent() {
637 # If no oldid, this is the current version.
638 if ( $this->getOldID() == 0 ) {
639 return true;
640 }
641 return $this->exists() && isset( $this->mRevision ) && $this->mRevision->isCurrent();
642 }
643
644 /**
645 * Loads everything except the text
646 * This isn't necessary for all uses, so it's only done if needed.
647 */
648 protected function loadLastEdit() {
649 if ( -1 != $this->mUser )
650 return;
651
652 # New or non-existent articles have no user information
653 $id = $this->getID();
654 if ( 0 == $id ) return;
655
656 $this->mLastRevision = Revision::loadFromPageId( wfGetDB( DB_MASTER ), $id );
657 if ( !is_null( $this->mLastRevision ) ) {
658 $this->mUser = $this->mLastRevision->getUser();
659 $this->mUserText = $this->mLastRevision->getUserText();
660 $this->mTimestamp = $this->mLastRevision->getTimestamp();
661 $this->mComment = $this->mLastRevision->getComment();
662 $this->mMinorEdit = $this->mLastRevision->isMinor();
663 $this->mRevIdFetched = $this->mLastRevision->getId();
664 }
665 }
666
667 public function getTimestamp() {
668 // Check if the field has been filled by ParserCache::get()
669 if ( !$this->mTimestamp ) {
670 $this->loadLastEdit();
671 }
672 return wfTimestamp( TS_MW, $this->mTimestamp );
673 }
674
675 public function getUser() {
676 $this->loadLastEdit();
677 return $this->mUser;
678 }
679
680 public function getUserText() {
681 $this->loadLastEdit();
682 return $this->mUserText;
683 }
684
685 public function getComment() {
686 $this->loadLastEdit();
687 return $this->mComment;
688 }
689
690 public function getMinorEdit() {
691 $this->loadLastEdit();
692 return $this->mMinorEdit;
693 }
694
695 /* Use this to fetch the rev ID used on page views */
696 public function getRevIdFetched() {
697 $this->loadLastEdit();
698 return $this->mRevIdFetched;
699 }
700
701 /**
702 * @param $limit Integer: default 0.
703 * @param $offset Integer: default 0.
704 */
705 public function getContributors( $limit = 0, $offset = 0 ) {
706 # XXX: this is expensive; cache this info somewhere.
707
708 $dbr = wfGetDB( DB_SLAVE );
709 $revTable = $dbr->tableName( 'revision' );
710 $userTable = $dbr->tableName( 'user' );
711
712 $pageId = $this->getId();
713
714 $user = $this->getUser();
715 if ( $user ) {
716 $excludeCond = "AND rev_user != $user";
717 } else {
718 $userText = $dbr->addQuotes( $this->getUserText() );
719 $excludeCond = "AND rev_user_text != $userText";
720 }
721
722 $deletedBit = $dbr->bitAnd( 'rev_deleted', Revision::DELETED_USER ); // username hidden?
723
724 $sql = "SELECT {$userTable}.*, rev_user_text as user_name, MAX(rev_timestamp) as timestamp
725 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
726 WHERE rev_page = $pageId
727 $excludeCond
728 AND $deletedBit = 0
729 GROUP BY rev_user, rev_user_text
730 ORDER BY timestamp DESC";
731
732 if ( $limit > 0 )
733 $sql = $dbr->limitResult( $sql, $limit, $offset );
734
735 $sql .= ' ' . $this->getSelectOptions();
736 $res = $dbr->query( $sql, __METHOD__ );
737
738 return new UserArrayFromResult( $res );
739 }
740
741 /**
742 * This is the default action of the index.php entry point: just view the
743 * page of the given title.
744 */
745 public function view() {
746 global $wgUser, $wgOut, $wgRequest, $wgContLang;
747 global $wgEnableParserCache, $wgStylePath, $wgParser;
748 global $wgUseTrackbacks, $wgUseFileCache;
749
750 wfProfileIn( __METHOD__ );
751
752 # Get variables from query string
753 $oldid = $this->getOldID();
754 $parserCache = ParserCache::singleton();
755
756 $parserOptions = clone $this->getParserOptions();
757 # Render printable version, use printable version cache
758 if ( $wgOut->isPrintable() ) {
759 $parserOptions->setIsPrintable( true );
760 }
761
762 # Try client and file cache
763 if ( $oldid === 0 && $this->checkTouched() ) {
764 global $wgUseETag;
765 if ( $wgUseETag ) {
766 $wgOut->setETag( $parserCache->getETag( $this, $parserOptions ) );
767 }
768 # Is is client cached?
769 if ( $wgOut->checkLastModified( $this->getTouched() ) ) {
770 wfDebug( __METHOD__ . ": done 304\n" );
771 wfProfileOut( __METHOD__ );
772 return;
773 # Try file cache
774 } else if ( $wgUseFileCache && $this->tryFileCache() ) {
775 wfDebug( __METHOD__ . ": done file cache\n" );
776 # tell wgOut that output is taken care of
777 $wgOut->disable();
778 $this->viewUpdates();
779 wfProfileOut( __METHOD__ );
780 return;
781 }
782 }
783
784 $sk = $wgUser->getSkin();
785
786 # getOldID may want us to redirect somewhere else
787 if ( $this->mRedirectUrl ) {
788 $wgOut->redirect( $this->mRedirectUrl );
789 wfDebug( __METHOD__ . ": redirecting due to oldid\n" );
790 wfProfileOut( __METHOD__ );
791 return;
792 }
793
794 $wgOut->setArticleFlag( true );
795 # Set page title (may be overridden by DISPLAYTITLE)
796 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
797
798 # If we got diff in the query, we want to see a diff page instead of the article.
799 if ( !is_null( $wgRequest->getVal( 'diff' ) ) ) {
800 wfDebug( __METHOD__ . ": showing diff page\n" );
801 $this->showDiffPage();
802 wfProfileOut( __METHOD__ );
803 return;
804 }
805
806 # Should the parser cache be used?
807 $useParserCache = $this->useParserCache( $oldid );
808 wfDebug( 'Article::view using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
809 if ( $wgUser->getOption( 'stubthreshold' ) ) {
810 wfIncrStats( 'pcache_miss_stub' );
811 }
812
813 # For the main page, overwrite the <title> element with the con-
814 # tents of 'pagetitle-view-mainpage' instead of the default (if
815 # that's not empty).
816 if ( $this->mTitle->equals( Title::newMainPage() )
817 && ( $m = wfMsgForContent( 'pagetitle-view-mainpage' ) ) !== '' )
818 {
819 $wgOut->setHTMLTitle( $m );
820 }
821
822 $wasRedirected = $this->showRedirectedFromHeader();
823 $this->showNamespaceHeader();
824
825 # Iterate through the possible ways of constructing the output text.
826 # Keep going until $outputDone is set, or we run out of things to do.
827 $pass = 0;
828 $outputDone = false;
829 while ( !$outputDone && ++$pass ) {
830 switch( $pass ) {
831 case 1:
832 wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$useParserCache ) );
833 break;
834
835 case 2:
836 # Try the parser cache
837 if ( $useParserCache ) {
838 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
839 if ( $this->mParserOutput !== false ) {
840 wfDebug( __METHOD__ . ": showing parser cache contents\n" );
841 $wgOut->addParserOutput( $this->mParserOutput );
842 # Ensure that UI elements requiring revision ID have
843 # the correct version information.
844 $wgOut->setRevisionId( $this->mLatest );
845 $outputDone = true;
846 }
847 }
848 break;
849
850 case 3:
851 $text = $this->getContent();
852 if ( $text === false || $this->getID() == 0 ) {
853 wfDebug( __METHOD__ . ": showing missing article\n" );
854 $this->showMissingArticle();
855 wfProfileOut( __METHOD__ );
856 return;
857 }
858
859 # Another whitelist check in case oldid is altering the title
860 if ( !$this->mTitle->userCanRead() ) {
861 wfDebug( __METHOD__ . ": denied on secondary read check\n" );
862 $wgOut->loginToUse();
863 $wgOut->output();
864 $wgOut->disable();
865 wfProfileOut( __METHOD__ );
866 return;
867 }
868
869 # Are we looking at an old revision
870 if ( $oldid && !is_null( $this->mRevision ) ) {
871 $this->setOldSubtitle( $oldid );
872 if ( !$this->showDeletedRevisionHeader() ) {
873 wfDebug( __METHOD__ . ": cannot view deleted revision\n" );
874 wfProfileOut( __METHOD__ );
875 return;
876 }
877 # If this "old" version is the current, then try the parser cache...
878 if ( $oldid === $this->getLatest() && $this->useParserCache( false ) ) {
879 $this->mParserOutput = $parserCache->get( $this, $parserOptions );
880 if ( $this->mParserOutput ) {
881 wfDebug( __METHOD__ . ": showing parser cache for current rev permalink\n" );
882 $wgOut->addParserOutput( $this->mParserOutput );
883 $wgOut->setRevisionId( $this->mLatest );
884 $this->showViewFooter();
885 $this->viewUpdates();
886 wfProfileOut( __METHOD__ );
887 return;
888 }
889 }
890 }
891
892 # Ensure that UI elements requiring revision ID have
893 # the correct version information.
894 $wgOut->setRevisionId( $this->getRevIdFetched() );
895
896 # Pages containing custom CSS or JavaScript get special treatment
897 if ( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
898 wfDebug( __METHOD__ . ": showing CSS/JS source\n" );
899 $this->showCssOrJsPage();
900 $outputDone = true;
901 } else if ( $rt = Title::newFromRedirectArray( $text ) ) {
902 wfDebug( __METHOD__ . ": showing redirect=no page\n" );
903 # Viewing a redirect page (e.g. with parameter redirect=no)
904 # Don't append the subtitle if this was an old revision
905 $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
906 # Parse just to get categories, displaytitle, etc.
907 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle, $parserOptions );
908 $wgOut->addParserOutputNoText( $this->mParserOutput );
909 $outputDone = true;
910 }
911 break;
912
913 case 4:
914 # Run the parse, protected by a pool counter
915 wfDebug( __METHOD__ . ": doing uncached parse\n" );
916 $key = $parserCache->getKey( $this, $parserOptions );
917 $poolCounter = PoolCounter::factory( 'Article::view', $key );
918 $dirtyCallback = $useParserCache ? array( $this, 'tryDirtyCache' ) : false;
919 $status = $poolCounter->executeProtected( array( $this, 'doViewParse' ), $dirtyCallback );
920
921 if ( !$status->isOK() ) {
922 # Connection or timeout error
923 $this->showPoolError( $status );
924 wfProfileOut( __METHOD__ );
925 return;
926 } else {
927 $outputDone = true;
928 }
929 break;
930
931 # Should be unreachable, but just in case...
932 default:
933 break 2;
934 }
935 }
936
937 # Now that we've filled $this->mParserOutput, we know whether
938 # there are any __NOINDEX__ tags on the page
939 $policy = $this->getRobotPolicy( 'view' );
940 $wgOut->setIndexPolicy( $policy['index'] );
941 $wgOut->setFollowPolicy( $policy['follow'] );
942
943 $this->showViewFooter();
944 $this->viewUpdates();
945 wfProfileOut( __METHOD__ );
946 }
947
948 /**
949 * Show a diff page according to current request variables. For use within
950 * Article::view() only, other callers should use the DifferenceEngine class.
951 */
952 public function showDiffPage() {
953 global $wgOut, $wgRequest, $wgUser;
954
955 $diff = $wgRequest->getVal( 'diff' );
956 $rcid = $wgRequest->getVal( 'rcid' );
957 $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
958 $purge = $wgRequest->getVal( 'action' ) == 'purge';
959 $unhide = $wgRequest->getInt( 'unhide' ) == 1;
960 $oldid = $this->getOldID();
961
962 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $unhide );
963 // DifferenceEngine directly fetched the revision:
964 $this->mRevIdFetched = $de->mNewid;
965 $de->showDiffPage( $diffOnly );
966
967 // Needed to get the page's current revision
968 $this->loadPageData();
969 if ( $diff == 0 || $diff == $this->mLatest ) {
970 # Run view updates for current revision only
971 $this->viewUpdates();
972 }
973 }
974
975 /**
976 * Show a page view for a page formatted as CSS or JavaScript. To be called by
977 * Article::view() only.
978 *
979 * This is hooked by SyntaxHighlight_GeSHi to do syntax highlighting of these
980 * page views.
981 */
982 public function showCssOrJsPage() {
983 global $wgOut;
984 $wgOut->addHTML( wfMsgExt( 'clearyourcache', 'parse' ) );
985 // Give hooks a chance to customise the output
986 if ( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
987 // Wrap the whole lot in a <pre> and don't parse
988 $m = array();
989 preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
990 $wgOut->addHTML( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
991 $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
992 $wgOut->addHTML( "\n</pre>\n" );
993 }
994 }
995
996 /**
997 * Get the robot policy to be used for the current action=view request.
998 * @return String the policy that should be set
999 * @deprecated use getRobotPolicy() instead, which returns an associative
1000 * array
1001 */
1002 public function getRobotPolicyForView() {
1003 wfDeprecated( __FUNC__ );
1004 $policy = $this->getRobotPolicy( 'view' );
1005 return $policy['index'] . ',' . $policy['follow'];
1006 }
1007
1008 /**
1009 * Get the robot policy to be used for the current view
1010 * @param $action String the action= GET parameter
1011 * @return Array the policy that should be set
1012 * TODO: actions other than 'view'
1013 */
1014 public function getRobotPolicy( $action ) {
1015
1016 global $wgOut, $wgArticleRobotPolicies, $wgNamespaceRobotPolicies;
1017 global $wgDefaultRobotPolicy, $wgRequest;
1018
1019 $ns = $this->mTitle->getNamespace();
1020 if ( $ns == NS_USER || $ns == NS_USER_TALK ) {
1021 # Don't index user and user talk pages for blocked users (bug 11443)
1022 if ( !$this->mTitle->isSubpage() ) {
1023 $block = new Block();
1024 if ( $block->load( $this->mTitle->getText() ) ) {
1025 return array( 'index' => 'noindex',
1026 'follow' => 'nofollow' );
1027 }
1028 }
1029 }
1030
1031 if ( $this->getID() === 0 || $this->getOldID() ) {
1032 # Non-articles (special pages etc), and old revisions
1033 return array( 'index' => 'noindex',
1034 'follow' => 'nofollow' );
1035 } elseif ( $wgOut->isPrintable() ) {
1036 # Discourage indexing of printable versions, but encourage following
1037 return array( 'index' => 'noindex',
1038 'follow' => 'follow' );
1039 } elseif ( $wgRequest->getInt( 'curid' ) ) {
1040 # For ?curid=x urls, disallow indexing
1041 return array( 'index' => 'noindex',
1042 'follow' => 'follow' );
1043 }
1044
1045 # Otherwise, construct the policy based on the various config variables.
1046 $policy = self::formatRobotPolicy( $wgDefaultRobotPolicy );
1047
1048 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
1049 # Honour customised robot policies for this namespace
1050 $policy = array_merge( $policy,
1051 self::formatRobotPolicy( $wgNamespaceRobotPolicies[$ns] ) );
1052 }
1053 if ( $this->mTitle->canUseNoindex() && is_object( $this->mParserOutput ) && $this->mParserOutput->getIndexPolicy() ) {
1054 # __INDEX__ and __NOINDEX__ magic words, if allowed. Incorporates
1055 # a final sanity check that we have really got the parser output.
1056 $policy = array_merge( $policy,
1057 array( 'index' => $this->mParserOutput->getIndexPolicy() ) );
1058 }
1059
1060 if ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
1061 # (bug 14900) site config can override user-defined __INDEX__ or __NOINDEX__
1062 $policy = array_merge( $policy,
1063 self::formatRobotPolicy( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) );
1064 }
1065
1066 return $policy;
1067
1068 }
1069
1070 /**
1071 * Converts a String robot policy into an associative array, to allow
1072 * merging of several policies using array_merge().
1073 * @param $policy Mixed, returns empty array on null/false/'', transparent
1074 * to already-converted arrays, converts String.
1075 * @return associative Array: 'index' => <indexpolicy>, 'follow' => <followpolicy>
1076 */
1077 public static function formatRobotPolicy( $policy ) {
1078 if ( is_array( $policy ) ) {
1079 return $policy;
1080 } elseif ( !$policy ) {
1081 return array();
1082 }
1083
1084 $policy = explode( ',', $policy );
1085 $policy = array_map( 'trim', $policy );
1086
1087 $arr = array();
1088 foreach ( $policy as $var ) {
1089 if ( in_array( $var, array( 'index', 'noindex' ) ) ) {
1090 $arr['index'] = $var;
1091 } elseif ( in_array( $var, array( 'follow', 'nofollow' ) ) ) {
1092 $arr['follow'] = $var;
1093 }
1094 }
1095 return $arr;
1096 }
1097
1098 /**
1099 * If this request is a redirect view, send "redirected from" subtitle to
1100 * $wgOut. Returns true if the header was needed, false if this is not a
1101 * redirect view. Handles both local and remote redirects.
1102 */
1103 public function showRedirectedFromHeader() {
1104 global $wgOut, $wgUser, $wgRequest, $wgRedirectSources;
1105
1106 $rdfrom = $wgRequest->getVal( 'rdfrom' );
1107 $sk = $wgUser->getSkin();
1108 if ( isset( $this->mRedirectedFrom ) ) {
1109 // This is an internally redirected page view.
1110 // We'll need a backlink to the source page for navigation.
1111 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
1112 $redir = $sk->link(
1113 $this->mRedirectedFrom,
1114 null,
1115 array(),
1116 array( 'redirect' => 'no' ),
1117 array( 'known', 'noclasses' )
1118 );
1119 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1120 $wgOut->setSubtitle( $s );
1121
1122 // Set the fragment if one was specified in the redirect
1123 if ( strval( $this->mTitle->getFragment() ) != '' ) {
1124 $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
1125 $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
1126 }
1127
1128 // Add a <link rel="canonical"> tag
1129 $wgOut->addLink( array( 'rel' => 'canonical',
1130 'href' => $this->mTitle->getLocalURL() )
1131 );
1132 return true;
1133 }
1134 } elseif ( $rdfrom ) {
1135 // This is an externally redirected view, from some other wiki.
1136 // If it was reported from a trusted site, supply a backlink.
1137 if ( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
1138 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
1139 $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
1140 $wgOut->setSubtitle( $s );
1141 return true;
1142 }
1143 }
1144 return false;
1145 }
1146
1147 /**
1148 * Show a header specific to the namespace currently being viewed, like
1149 * [[MediaWiki:Talkpagetext]]. For Article::view().
1150 */
1151 public function showNamespaceHeader() {
1152 global $wgOut;
1153 if ( $this->mTitle->isTalkPage() ) {
1154 $msg = wfMsgNoTrans( 'talkpageheader' );
1155 if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
1156 $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
1157 }
1158 }
1159 }
1160
1161 /**
1162 * Show the footer section of an ordinary page view
1163 */
1164 public function showViewFooter() {
1165 global $wgOut, $wgUseTrackbacks, $wgRequest;
1166 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
1167 if ( $this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid( $this->mTitle->getText() ) ) {
1168 $wgOut->addWikiMsg( 'anontalkpagetext' );
1169 }
1170
1171 # If we have been passed an &rcid= parameter, we want to give the user a
1172 # chance to mark this new article as patrolled.
1173 $this->showPatrolFooter();
1174
1175 # Trackbacks
1176 if ( $wgUseTrackbacks ) {
1177 $this->addTrackbacks();
1178 }
1179 }
1180
1181 /**
1182 * If patrol is possible, output a patrol UI box. This is called from the
1183 * footer section of ordinary page views. If patrol is not possible or not
1184 * desired, does nothing.
1185 */
1186 public function showPatrolFooter() {
1187 global $wgOut, $wgRequest, $wgUser;
1188 $rcid = $wgRequest->getVal( 'rcid' );
1189
1190 if ( !$rcid || !$this->mTitle->exists() || !$this->mTitle->quickUserCan( 'patrol' ) ) {
1191 return;
1192 }
1193
1194 $sk = $wgUser->getSkin();
1195
1196 $wgOut->addHTML(
1197 "<div class='patrollink'>" .
1198 wfMsgHtml(
1199 'markaspatrolledlink',
1200 $sk->link(
1201 $this->mTitle,
1202 wfMsgHtml( 'markaspatrolledtext' ),
1203 array(),
1204 array(
1205 'action' => 'markpatrolled',
1206 'rcid' => $rcid
1207 ),
1208 array( 'known', 'noclasses' )
1209 )
1210 ) .
1211 '</div>'
1212 );
1213 }
1214
1215 /**
1216 * Show the error text for a missing article. For articles in the MediaWiki
1217 * namespace, show the default message text. To be called from Article::view().
1218 */
1219 public function showMissingArticle() {
1220 global $wgOut, $wgRequest, $wgUser;
1221
1222 # Show info in user (talk) namespace. Does the user exist? Is he blocked?
1223 if ( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
1224 $parts = explode( '/', $this->mTitle->getText() );
1225 $rootPart = $parts[0];
1226 $user = User::newFromName( $rootPart, false /* allow IP users*/ );
1227 $ip = User::isIP( $rootPart );
1228 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
1229 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n\$1</div>",
1230 array( 'userpage-userdoesnotexist-view', $rootPart ) );
1231 } else if ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
1232 LogEventsList::showLogExtract(
1233 $wgOut,
1234 'block',
1235 $user->getUserPage()->getPrefixedText(),
1236 '',
1237 array(
1238 'lim' => 1,
1239 'showIfEmpty' => false,
1240 'msgKey' => array(
1241 'blocked-notice-logextract',
1242 $user->getName() # Support GENDER in notice
1243 )
1244 )
1245 );
1246 }
1247 }
1248 wfRunHooks( 'ShowMissingArticle', array( $this ) );
1249 # Show delete and move logs
1250 LogEventsList::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle->getPrefixedText(), '',
1251 array( 'lim' => 10,
1252 'conds' => array( "log_action != 'revision'" ),
1253 'showIfEmpty' => false,
1254 'msgKey' => array( 'moveddeleted-notice' ) )
1255 );
1256
1257 # Show error message
1258 $oldid = $this->getOldID();
1259 if ( $oldid ) {
1260 $text = wfMsgNoTrans( 'missing-article',
1261 $this->mTitle->getPrefixedText(),
1262 wfMsgNoTrans( 'missingarticle-rev', $oldid ) );
1263 } elseif ( $this->mTitle->getNamespace() === NS_MEDIAWIKI ) {
1264 // Use the default message text
1265 $text = $this->getContent();
1266 } else {
1267 $createErrors = $this->mTitle->getUserPermissionsErrors( 'create', $wgUser );
1268 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
1269 $errors = array_merge( $createErrors, $editErrors );
1270
1271 if ( !count( $errors ) )
1272 $text = wfMsgNoTrans( 'noarticletext' );
1273 else
1274 $text = wfMsgNoTrans( 'noarticletext-nopermission' );
1275 }
1276 $text = "<div class='noarticletext'>\n$text\n</div>";
1277 if ( !$this->hasViewableContent() ) {
1278 // If there's no backing content, send a 404 Not Found
1279 // for better machine handling of broken links.
1280 $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
1281 }
1282 $wgOut->addWikiText( $text );
1283 }
1284
1285 /**
1286 * If the revision requested for view is deleted, check permissions.
1287 * Send either an error message or a warning header to $wgOut.
1288 * Returns true if the view is allowed, false if not.
1289 */
1290 public function showDeletedRevisionHeader() {
1291 global $wgOut, $wgRequest;
1292 if ( !$this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1293 // Not deleted
1294 return true;
1295 }
1296 // If the user is not allowed to see it...
1297 if ( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1298 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1299 'rev-deleted-text-permission' );
1300 return false;
1301 // If the user needs to confirm that they want to see it...
1302 } else if ( $wgRequest->getInt( 'unhide' ) != 1 ) {
1303 # Give explanation and add a link to view the revision...
1304 $oldid = intval( $this->getOldID() );
1305 $link = $this->mTitle->getFullUrl( "oldid={$oldid}&unhide=1" );
1306 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1307 'rev-suppressed-text-unhide' : 'rev-deleted-text-unhide';
1308 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
1309 array( $msg, $link ) );
1310 return false;
1311 // We are allowed to see...
1312 } else {
1313 $msg = $this->mRevision->isDeleted( Revision::DELETED_RESTRICTED ) ?
1314 'rev-suppressed-text-view' : 'rev-deleted-text-view';
1315 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", $msg );
1316 return true;
1317 }
1318 }
1319
1320 /*
1321 * Should the parser cache be used?
1322 */
1323 public function useParserCache( $oldid ) {
1324 global $wgUser, $wgEnableParserCache;
1325
1326 return $wgEnableParserCache
1327 && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
1328 && $this->exists()
1329 && empty( $oldid )
1330 && !$this->mTitle->isCssOrJsPage()
1331 && !$this->mTitle->isCssJsSubpage();
1332 }
1333
1334 /**
1335 * Execute the uncached parse for action=view
1336 */
1337 public function doViewParse() {
1338 global $wgOut;
1339 $oldid = $this->getOldID();
1340 $useParserCache = $this->useParserCache( $oldid );
1341 $parserOptions = clone $this->getParserOptions();
1342 # Render printable version, use printable version cache
1343 $parserOptions->setIsPrintable( $wgOut->isPrintable() );
1344 # Don't show section-edit links on old revisions... this way lies madness.
1345 $parserOptions->setEditSection( $this->isCurrent() );
1346 $useParserCache = $this->useParserCache( $oldid );
1347 $this->outputWikiText( $this->getContent(), $useParserCache, $parserOptions );
1348 }
1349
1350 /**
1351 * Try to fetch an expired entry from the parser cache. If it is present,
1352 * output it and return true. If it is not present, output nothing and
1353 * return false. This is used as a callback function for
1354 * PoolCounter::executeProtected().
1355 */
1356 public function tryDirtyCache() {
1357 global $wgOut;
1358 $parserCache = ParserCache::singleton();
1359 $options = $this->getParserOptions();
1360 $options->setIsPrintable( $wgOut->isPrintable() );
1361 $output = $parserCache->getDirty( $this, $options );
1362 if ( $output ) {
1363 wfDebug( __METHOD__ . ": sending dirty output\n" );
1364 wfDebugLog( 'dirty', "dirty output " . $parserCache->getKey( $this, $options ) . "\n" );
1365 $wgOut->setSquidMaxage( 0 );
1366 $this->mParserOutput = $output;
1367 $wgOut->addParserOutput( $output );
1368 $wgOut->addHTML( "<!-- parser cache is expired, sending anyway due to pool overload-->\n" );
1369 return true;
1370 } else {
1371 wfDebugLog( 'dirty', "dirty missing\n" );
1372 wfDebug( __METHOD__ . ": no dirty cache\n" );
1373 return false;
1374 }
1375 }
1376
1377 /**
1378 * Show an error page for an error from the pool counter.
1379 * @param $status Status
1380 */
1381 public function showPoolError( $status ) {
1382 global $wgOut;
1383 $wgOut->clearHTML(); // for release() errors
1384 $wgOut->enableClientCache( false );
1385 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1386 $wgOut->addWikiText(
1387 '<div class="errorbox">' .
1388 $status->getWikiText( false, 'view-pool-error' ) .
1389 '</div>'
1390 );
1391 }
1392
1393 /**
1394 * View redirect
1395 * @param $target Title object or Array of destination(s) to redirect
1396 * @param $appendSubtitle Boolean [optional]
1397 * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
1398 */
1399 public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
1400 global $wgOut, $wgContLang, $wgStylePath, $wgUser;
1401 # Display redirect
1402 if ( !is_array( $target ) ) {
1403 $target = array( $target );
1404 }
1405 $imageDir = $wgContLang->getDir();
1406 $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
1407 $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
1408 $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
1409
1410 if ( $appendSubtitle ) {
1411 $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
1412 }
1413 $sk = $wgUser->getSkin();
1414 // the loop prepends the arrow image before the link, so the first case needs to be outside
1415 $title = array_shift( $target );
1416 if ( $forceKnown ) {
1417 $link = $sk->link(
1418 $title,
1419 htmlspecialchars( $title->getFullText() ),
1420 array(),
1421 array(),
1422 array( 'known', 'noclasses' )
1423 );
1424 } else {
1425 $link = $sk->link( $title, htmlspecialchars( $title->getFullText() ) );
1426 }
1427 // automatically append redirect=no to each link, since most of them are redirect pages themselves
1428 foreach ( $target as $rt ) {
1429 if ( $forceKnown ) {
1430 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1431 . $sk->link(
1432 $rt,
1433 htmlspecialchars( $rt->getFullText() ),
1434 array(),
1435 array(),
1436 array( 'known', 'noclasses' )
1437 );
1438 } else {
1439 $link .= '<img src="' . $imageUrl2 . '" alt="' . $alt2 . ' " />'
1440 . $sk->link( $rt, htmlspecialchars( $rt->getFullText() ) );
1441 }
1442 }
1443 return '<img src="' . $imageUrl . '" alt="#REDIRECT " />' .
1444 '<span class="redirectText">' . $link . '</span>';
1445
1446 }
1447
1448 public function addTrackbacks() {
1449 global $wgOut, $wgUser;
1450 $dbr = wfGetDB( DB_SLAVE );
1451 $tbs = $dbr->select( 'trackbacks',
1452 array( 'tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name' ),
1453 array( 'tb_page' => $this->getID() )
1454 );
1455 if ( !$dbr->numRows( $tbs ) ) return;
1456
1457 $tbtext = "";
1458 while ( $o = $dbr->fetchObject( $tbs ) ) {
1459 $rmvtxt = "";
1460 if ( $wgUser->isAllowed( 'trackback' ) ) {
1461 $delurl = $this->mTitle->getFullURL( "action=deletetrackback&tbid=" .
1462 $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
1463 $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
1464 }
1465 $tbtext .= "\n";
1466 $tbtext .= wfMsg( strlen( $o->tb_ex ) ? 'trackbackexcerpt' : 'trackback',
1467 $o->tb_title,
1468 $o->tb_url,
1469 $o->tb_ex,
1470 $o->tb_name,
1471 $rmvtxt );
1472 }
1473 $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
1474 $this->mTitle->invalidateCache();
1475 }
1476
1477 public function deletetrackback() {
1478 global $wgUser, $wgRequest, $wgOut;
1479 if ( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
1480 $wgOut->addWikiMsg( 'sessionfailure' );
1481 return;
1482 }
1483
1484 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
1485 if ( count( $permission_errors ) ) {
1486 $wgOut->showPermissionsErrorPage( $permission_errors );
1487 return;
1488 }
1489
1490 $db = wfGetDB( DB_MASTER );
1491 $db->delete( 'trackbacks', array( 'tb_id' => $wgRequest->getInt( 'tbid' ) ) );
1492
1493 $wgOut->addWikiMsg( 'trackbackdeleteok' );
1494 $this->mTitle->invalidateCache();
1495 }
1496
1497 public function render() {
1498 global $wgOut;
1499 $wgOut->setArticleBodyOnly( true );
1500 $this->view();
1501 }
1502
1503 /**
1504 * Handle action=purge
1505 */
1506 public function purge() {
1507 global $wgUser, $wgRequest, $wgOut;
1508 if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
1509 if ( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1510 $this->doPurge();
1511 $this->view();
1512 }
1513 } else {
1514 $action = htmlspecialchars( $wgRequest->getRequestURL() );
1515 $button = wfMsgExt( 'confirm_purge_button', array( 'escapenoentities' ) );
1516 $form = "<form method=\"post\" action=\"$action\">\n" .
1517 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1518 "</form>\n";
1519 $top = wfMsgExt( 'confirm-purge-top', array( 'parse' ) );
1520 $bottom = wfMsgExt( 'confirm-purge-bottom', array( 'parse' ) );
1521 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1522 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1523 $wgOut->addHTML( $top . $form . $bottom );
1524 }
1525 }
1526
1527 /**
1528 * Perform the actions of a page purging
1529 */
1530 public function doPurge() {
1531 global $wgUseSquid;
1532 // Invalidate the cache
1533 $this->mTitle->invalidateCache();
1534
1535 if ( $wgUseSquid ) {
1536 // Commit the transaction before the purge is sent
1537 $dbw = wfGetDB( DB_MASTER );
1538 $dbw->commit();
1539
1540 // Send purge
1541 $update = SquidUpdate::newSimplePurge( $this->mTitle );
1542 $update->doUpdate();
1543 }
1544 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1545 global $wgMessageCache;
1546 if ( $this->getID() == 0 ) {
1547 $text = false;
1548 } else {
1549 $text = $this->getRawText();
1550 }
1551 $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
1552 }
1553 }
1554
1555 /**
1556 * Insert a new empty page record for this article.
1557 * This *must* be followed up by creating a revision
1558 * and running $this->updateToLatest( $rev_id );
1559 * or else the record will be left in a funky state.
1560 * Best if all done inside a transaction.
1561 *
1562 * @param $dbw Database
1563 * @return int The newly created page_id key, or false if the title already existed
1564 * @private
1565 */
1566 public function insertOn( $dbw ) {
1567 wfProfileIn( __METHOD__ );
1568
1569 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1570 $dbw->insert( 'page', array(
1571 'page_id' => $page_id,
1572 'page_namespace' => $this->mTitle->getNamespace(),
1573 'page_title' => $this->mTitle->getDBkey(),
1574 'page_counter' => 0,
1575 'page_restrictions' => '',
1576 'page_is_redirect' => 0, # Will set this shortly...
1577 'page_is_new' => 1,
1578 'page_random' => wfRandom(),
1579 'page_touched' => $dbw->timestamp(),
1580 'page_latest' => 0, # Fill this in shortly...
1581 'page_len' => 0, # Fill this in shortly...
1582 ), __METHOD__, 'IGNORE' );
1583
1584 $affected = $dbw->affectedRows();
1585 if ( $affected ) {
1586 $newid = $dbw->insertId();
1587 $this->mTitle->resetArticleId( $newid );
1588 }
1589 wfProfileOut( __METHOD__ );
1590 return $affected ? $newid : false;
1591 }
1592
1593 /**
1594 * Update the page record to point to a newly saved revision.
1595 *
1596 * @param $dbw Database object
1597 * @param $revision Revision: For ID number, and text used to set
1598 length and redirect status fields
1599 * @param $lastRevision Integer: if given, will not overwrite the page field
1600 * when different from the currently set value.
1601 * Giving 0 indicates the new page flag should be set
1602 * on.
1603 * @param $lastRevIsRedirect Boolean: if given, will optimize adding and
1604 * removing rows in redirect table.
1605 * @return bool true on success, false on failure
1606 * @private
1607 */
1608 public function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1609 wfProfileIn( __METHOD__ );
1610
1611 $text = $revision->getText();
1612 $rt = Title::newFromRedirect( $text );
1613
1614 $conditions = array( 'page_id' => $this->getId() );
1615 if ( !is_null( $lastRevision ) ) {
1616 # An extra check against threads stepping on each other
1617 $conditions['page_latest'] = $lastRevision;
1618 }
1619
1620 $dbw->update( 'page',
1621 array( /* SET */
1622 'page_latest' => $revision->getId(),
1623 'page_touched' => $dbw->timestamp(),
1624 'page_is_new' => ( $lastRevision === 0 ) ? 1 : 0,
1625 'page_is_redirect' => $rt !== null ? 1 : 0,
1626 'page_len' => strlen( $text ),
1627 ),
1628 $conditions,
1629 __METHOD__ );
1630
1631 $result = $dbw->affectedRows() != 0;
1632 if ( $result ) {
1633 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1634 }
1635
1636 wfProfileOut( __METHOD__ );
1637 return $result;
1638 }
1639
1640 /**
1641 * Add row to the redirect table if this is a redirect, remove otherwise.
1642 *
1643 * @param $dbw Database
1644 * @param $redirectTitle a title object pointing to the redirect target,
1645 * or NULL if this is not a redirect
1646 * @param $lastRevIsRedirect If given, will optimize adding and
1647 * removing rows in redirect table.
1648 * @return bool true on success, false on failure
1649 * @private
1650 */
1651 public function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1652 // Always update redirects (target link might have changed)
1653 // Update/Insert if we don't know if the last revision was a redirect or not
1654 // Delete if changing from redirect to non-redirect
1655 $isRedirect = !is_null( $redirectTitle );
1656 if ( $isRedirect || is_null( $lastRevIsRedirect ) || $lastRevIsRedirect !== $isRedirect ) {
1657 wfProfileIn( __METHOD__ );
1658 if ( $isRedirect ) {
1659 // This title is a redirect, Add/Update row in the redirect table
1660 $set = array( /* SET */
1661 'rd_namespace' => $redirectTitle->getNamespace(),
1662 'rd_title' => $redirectTitle->getDBkey(),
1663 'rd_from' => $this->getId(),
1664 );
1665 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
1666 } else {
1667 // This is not a redirect, remove row from redirect table
1668 $where = array( 'rd_from' => $this->getId() );
1669 $dbw->delete( 'redirect', $where, __METHOD__ );
1670 }
1671 if ( $this->getTitle()->getNamespace() == NS_FILE ) {
1672 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $this->getTitle() );
1673 }
1674 wfProfileOut( __METHOD__ );
1675 return ( $dbw->affectedRows() != 0 );
1676 }
1677 return true;
1678 }
1679
1680 /**
1681 * If the given revision is newer than the currently set page_latest,
1682 * update the page record. Otherwise, do nothing.
1683 *
1684 * @param $dbw Database object
1685 * @param $revision Revision object
1686 */
1687 public function updateIfNewerOn( &$dbw, $revision ) {
1688 wfProfileIn( __METHOD__ );
1689 $row = $dbw->selectRow(
1690 array( 'revision', 'page' ),
1691 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1692 array(
1693 'page_id' => $this->getId(),
1694 'page_latest=rev_id' ),
1695 __METHOD__ );
1696 if ( $row ) {
1697 if ( wfTimestamp( TS_MW, $row->rev_timestamp ) >= $revision->getTimestamp() ) {
1698 wfProfileOut( __METHOD__ );
1699 return false;
1700 }
1701 $prev = $row->rev_id;
1702 $lastRevIsRedirect = (bool)$row->page_is_redirect;
1703 } else {
1704 # No or missing previous revision; mark the page as new
1705 $prev = 0;
1706 $lastRevIsRedirect = null;
1707 }
1708 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1709 wfProfileOut( __METHOD__ );
1710 return $ret;
1711 }
1712
1713 /**
1714 * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
1715 * @return string Complete article text, or null if error
1716 */
1717 public function replaceSection( $section, $text, $summary = '', $edittime = null ) {
1718 wfProfileIn( __METHOD__ );
1719 if ( strval( $section ) == '' ) {
1720 // Whole-page edit; let the whole text through
1721 } else {
1722 if ( is_null( $edittime ) ) {
1723 $rev = Revision::newFromTitle( $this->mTitle );
1724 } else {
1725 $dbw = wfGetDB( DB_MASTER );
1726 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1727 }
1728 if ( !$rev ) {
1729 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1730 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1731 return null;
1732 }
1733 $oldtext = $rev->getText();
1734
1735 if ( $section == 'new' ) {
1736 # Inserting a new section
1737 $subject = $summary ? wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" : '';
1738 $text = strlen( trim( $oldtext ) ) > 0
1739 ? "{$oldtext}\n\n{$subject}{$text}"
1740 : "{$subject}{$text}";
1741 } else {
1742 # Replacing an existing section; roll out the big guns
1743 global $wgParser;
1744 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1745 }
1746 }
1747 wfProfileOut( __METHOD__ );
1748 return $text;
1749 }
1750
1751 /**
1752 * This function is not deprecated until somebody fixes the core not to use
1753 * it. Nevertheless, use Article::doEdit() instead.
1754 */
1755 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC = false, $comment = false, $bot = false ) {
1756 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1757 ( $isminor ? EDIT_MINOR : 0 ) |
1758 ( $suppressRC ? EDIT_SUPPRESS_RC : 0 ) |
1759 ( $bot ? EDIT_FORCE_BOT : 0 );
1760
1761 # If this is a comment, add the summary as headline
1762 if ( $comment && $summary != "" ) {
1763 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $summary ) . "\n\n" . $text;
1764 }
1765
1766 $this->doEdit( $text, $summary, $flags );
1767
1768 $dbw = wfGetDB( DB_MASTER );
1769 if ( $watchthis ) {
1770 if ( !$this->mTitle->userIsWatching() ) {
1771 $dbw->begin();
1772 $this->doWatch();
1773 $dbw->commit();
1774 }
1775 } else {
1776 if ( $this->mTitle->userIsWatching() ) {
1777 $dbw->begin();
1778 $this->doUnwatch();
1779 $dbw->commit();
1780 }
1781 }
1782 $this->doRedirect( $this->isRedirect( $text ) );
1783 }
1784
1785 /**
1786 * @deprecated use Article::doEdit()
1787 */
1788 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1789 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1790 ( $minor ? EDIT_MINOR : 0 ) |
1791 ( $forceBot ? EDIT_FORCE_BOT : 0 );
1792
1793 $status = $this->doEdit( $text, $summary, $flags );
1794 if ( !$status->isOK() ) {
1795 return false;
1796 }
1797
1798 $dbw = wfGetDB( DB_MASTER );
1799 if ( $watchthis ) {
1800 if ( !$this->mTitle->userIsWatching() ) {
1801 $dbw->begin();
1802 $this->doWatch();
1803 $dbw->commit();
1804 }
1805 } else {
1806 if ( $this->mTitle->userIsWatching() ) {
1807 $dbw->begin();
1808 $this->doUnwatch();
1809 $dbw->commit();
1810 }
1811 }
1812
1813 $extraQuery = ''; // Give extensions a chance to modify URL query on update
1814 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this, &$sectionanchor, &$extraQuery ) );
1815
1816 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor, $extraQuery );
1817 return true;
1818 }
1819
1820 /**
1821 * Article::doEdit()
1822 *
1823 * Change an existing article or create a new article. Updates RC and all necessary caches,
1824 * optionally via the deferred update array.
1825 *
1826 * $wgUser must be set before calling this function.
1827 *
1828 * @param $text String: new text
1829 * @param $summary String: edit summary
1830 * @param $flags Integer bitfield:
1831 * EDIT_NEW
1832 * Article is known or assumed to be non-existent, create a new one
1833 * EDIT_UPDATE
1834 * Article is known or assumed to be pre-existing, update it
1835 * EDIT_MINOR
1836 * Mark this edit minor, if the user is allowed to do so
1837 * EDIT_SUPPRESS_RC
1838 * Do not log the change in recentchanges
1839 * EDIT_FORCE_BOT
1840 * Mark the edit a "bot" edit regardless of user rights
1841 * EDIT_DEFER_UPDATES
1842 * Defer some of the updates until the end of index.php
1843 * EDIT_AUTOSUMMARY
1844 * Fill in blank summaries with generated text where possible
1845 *
1846 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1847 * If EDIT_UPDATE is specified and the article doesn't exist, the function will an
1848 * edit-gone-missing error. If EDIT_NEW is specified and the article does exist, an
1849 * edit-already-exists error will be returned. These two conditions are also possible with
1850 * auto-detection due to MediaWiki's performance-optimised locking strategy.
1851 *
1852 * @param $baseRevId the revision ID this edit was based off, if any
1853 * @param $user Optional user object, $wgUser will be used if not passed
1854 *
1855 * @return Status object. Possible errors:
1856 * edit-hook-aborted: The ArticleSave hook aborted the edit but didn't set the fatal flag of $status
1857 * edit-gone-missing: In update mode, but the article didn't exist
1858 * edit-conflict: In update mode, the article changed unexpectedly
1859 * edit-no-change: Warning that the text was the same as before
1860 * edit-already-exists: In creation mode, but the article already exists
1861 *
1862 * Extensions may define additional errors.
1863 *
1864 * $return->value will contain an associative array with members as follows:
1865 * new: Boolean indicating if the function attempted to create a new article
1866 * revision: The revision object for the inserted revision, or null
1867 *
1868 * Compatibility note: this function previously returned a boolean value indicating success/failure
1869 */
1870 public function doEdit( $text, $summary, $flags = 0, $baseRevId = false, $user = null ) {
1871 global $wgUser, $wgDBtransactions, $wgUseAutomaticEditSummaries;
1872
1873 # Low-level sanity check
1874 if ( $this->mTitle->getText() == '' ) {
1875 throw new MWException( 'Something is trying to edit an article with an empty title' );
1876 }
1877
1878 wfProfileIn( __METHOD__ );
1879
1880 $user = is_null( $user ) ? $wgUser : $user;
1881 $status = Status::newGood( array() );
1882
1883 # Load $this->mTitle->getArticleID() and $this->mLatest if it's not already
1884 $this->loadPageData();
1885
1886 if ( !( $flags & EDIT_NEW ) && !( $flags & EDIT_UPDATE ) ) {
1887 $aid = $this->mTitle->getArticleID();
1888 if ( $aid ) {
1889 $flags |= EDIT_UPDATE;
1890 } else {
1891 $flags |= EDIT_NEW;
1892 }
1893 }
1894
1895 if ( !wfRunHooks( 'ArticleSave', array( &$this, &$user, &$text, &$summary,
1896 $flags & EDIT_MINOR, null, null, &$flags, &$status ) ) )
1897 {
1898 wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
1899 wfProfileOut( __METHOD__ );
1900 if ( $status->isOK() ) {
1901 $status->fatal( 'edit-hook-aborted' );
1902 }
1903 return $status;
1904 }
1905
1906 # Silently ignore EDIT_MINOR if not allowed
1907 $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed( 'minoredit' );
1908 $bot = $flags & EDIT_FORCE_BOT;
1909
1910 $oldtext = $this->getRawText(); // current revision
1911 $oldsize = strlen( $oldtext );
1912
1913 # Provide autosummaries if one is not provided and autosummaries are enabled.
1914 if ( $wgUseAutomaticEditSummaries && $flags & EDIT_AUTOSUMMARY && $summary == '' ) {
1915 $summary = $this->getAutosummary( $oldtext, $text, $flags );
1916 }
1917
1918 $editInfo = $this->prepareTextForEdit( $text );
1919 $text = $editInfo->pst;
1920 $newsize = strlen( $text );
1921
1922 $dbw = wfGetDB( DB_MASTER );
1923 $now = wfTimestampNow();
1924 $this->mTimestamp = $now;
1925
1926 if ( $flags & EDIT_UPDATE ) {
1927 # Update article, but only if changed.
1928 $status->value['new'] = false;
1929 # Make sure the revision is either completely inserted or not inserted at all
1930 if ( !$wgDBtransactions ) {
1931 $userAbort = ignore_user_abort( true );
1932 }
1933
1934 $revisionId = 0;
1935
1936 $changed = ( strcmp( $text, $oldtext ) != 0 );
1937
1938 if ( $changed ) {
1939 $this->mGoodAdjustment = (int)$this->isCountable( $text )
1940 - (int)$this->isCountable( $oldtext );
1941 $this->mTotalAdjustment = 0;
1942
1943 if ( !$this->mLatest ) {
1944 # Article gone missing
1945 wfDebug( __METHOD__ . ": EDIT_UPDATE specified but article doesn't exist\n" );
1946 $status->fatal( 'edit-gone-missing' );
1947 wfProfileOut( __METHOD__ );
1948 return $status;
1949 }
1950
1951 $revision = new Revision( array(
1952 'page' => $this->getId(),
1953 'comment' => $summary,
1954 'minor_edit' => $isminor,
1955 'text' => $text,
1956 'parent_id' => $this->mLatest,
1957 'user' => $user->getId(),
1958 'user_text' => $user->getName(),
1959 ) );
1960
1961 $dbw->begin();
1962 $revisionId = $revision->insertOn( $dbw );
1963
1964 # Update page
1965 #
1966 # Note that we use $this->mLatest instead of fetching a value from the master DB
1967 # during the course of this function. This makes sure that EditPage can detect
1968 # edit conflicts reliably, either by $ok here, or by $article->getTimestamp()
1969 # before this function is called. A previous function used a separate query, this
1970 # creates a window where concurrent edits can cause an ignored edit conflict.
1971 $ok = $this->updateRevisionOn( $dbw, $revision, $this->mLatest );
1972
1973 if ( !$ok ) {
1974 /* Belated edit conflict! Run away!! */
1975 $status->fatal( 'edit-conflict' );
1976 # Delete the invalid revision if the DB is not transactional
1977 if ( !$wgDBtransactions ) {
1978 $dbw->delete( 'revision', array( 'rev_id' => $revisionId ), __METHOD__ );
1979 }
1980 $revisionId = 0;
1981 $dbw->rollback();
1982 } else {
1983 global $wgUseRCPatrol;
1984 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, $baseRevId, $user ) );
1985 # Update recentchanges
1986 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
1987 # Mark as patrolled if the user can do so
1988 $patrolled = $wgUseRCPatrol && $this->mTitle->userCan( 'autopatrol' );
1989 # Add RC row to the DB
1990 $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
1991 $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1992 $revisionId, $patrolled
1993 );
1994 # Log auto-patrolled edits
1995 if ( $patrolled ) {
1996 PatrolLog::record( $rc, true );
1997 }
1998 }
1999 $user->incEditCount();
2000 $dbw->commit();
2001 }
2002 } else {
2003 $status->warning( 'edit-no-change' );
2004 $revision = null;
2005 // Keep the same revision ID, but do some updates on it
2006 $revisionId = $this->getRevIdFetched();
2007 // Update page_touched, this is usually implicit in the page update
2008 // Other cache updates are done in onArticleEdit()
2009 $this->mTitle->invalidateCache();
2010 }
2011
2012 if ( !$wgDBtransactions ) {
2013 ignore_user_abort( $userAbort );
2014 }
2015 // Now that ignore_user_abort is restored, we can respond to fatal errors
2016 if ( !$status->isOK() ) {
2017 wfProfileOut( __METHOD__ );
2018 return $status;
2019 }
2020
2021 # Invalidate cache of this article and all pages using this article
2022 # as a template. Partly deferred.
2023 Article::onArticleEdit( $this->mTitle );
2024 # Update links tables, site stats, etc.
2025 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
2026 } else {
2027 # Create new article
2028 $status->value['new'] = true;
2029
2030 # Set statistics members
2031 # We work out if it's countable after PST to avoid counter drift
2032 # when articles are created with {{subst:}}
2033 $this->mGoodAdjustment = (int)$this->isCountable( $text );
2034 $this->mTotalAdjustment = 1;
2035
2036 $dbw->begin();
2037
2038 # Add the page record; stake our claim on this title!
2039 # This will return false if the article already exists
2040 $newid = $this->insertOn( $dbw );
2041
2042 if ( $newid === false ) {
2043 $dbw->rollback();
2044 $status->fatal( 'edit-already-exists' );
2045 wfProfileOut( __METHOD__ );
2046 return $status;
2047 }
2048
2049 # Save the revision text...
2050 $revision = new Revision( array(
2051 'page' => $newid,
2052 'comment' => $summary,
2053 'minor_edit' => $isminor,
2054 'text' => $text,
2055 'user' => $user->getId(),
2056 'user_text' => $user->getName(),
2057 ) );
2058 $revisionId = $revision->insertOn( $dbw );
2059
2060 $this->mTitle->resetArticleID( $newid );
2061
2062 # Update the page record with revision data
2063 $this->updateRevisionOn( $dbw, $revision, 0 );
2064
2065 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $user ) );
2066 # Update recentchanges
2067 if ( !( $flags & EDIT_SUPPRESS_RC ) ) {
2068 global $wgUseRCPatrol, $wgUseNPPatrol;
2069 # Mark as patrolled if the user can do so
2070 $patrolled = ( $wgUseRCPatrol || $wgUseNPPatrol ) && $this->mTitle->userCan( 'autopatrol' );
2071 # Add RC row to the DB
2072 $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
2073 '', strlen( $text ), $revisionId, $patrolled );
2074 # Log auto-patrolled edits
2075 if ( $patrolled ) {
2076 PatrolLog::record( $rc, true );
2077 }
2078 }
2079 $user->incEditCount();
2080 $dbw->commit();
2081
2082 # Update links, etc.
2083 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
2084
2085 # Clear caches
2086 Article::onArticleCreate( $this->mTitle );
2087
2088 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$user, $text, $summary,
2089 $flags & EDIT_MINOR, null, null, &$flags, $revision ) );
2090 }
2091
2092 # Do updates right now unless deferral was requested
2093 if ( !( $flags & EDIT_DEFER_UPDATES ) ) {
2094 wfDoUpdates();
2095 }
2096
2097 // Return the new revision (or null) to the caller
2098 $status->value['revision'] = $revision;
2099
2100 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
2101 $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
2102
2103 wfProfileOut( __METHOD__ );
2104 return $status;
2105 }
2106
2107 /**
2108 * @deprecated wrapper for doRedirect
2109 */
2110 public function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
2111 wfDeprecated( __METHOD__ );
2112 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
2113 }
2114
2115 /**
2116 * Output a redirect back to the article.
2117 * This is typically used after an edit.
2118 *
2119 * @param $noRedir Boolean: add redirect=no
2120 * @param $sectionAnchor String: section to redirect to, including "#"
2121 * @param $extraQuery String: extra query params
2122 */
2123 public function doRedirect( $noRedir = false, $sectionAnchor = '', $extraQuery = '' ) {
2124 global $wgOut;
2125 if ( $noRedir ) {
2126 $query = 'redirect=no';
2127 if ( $extraQuery )
2128 $query .= "&$query";
2129 } else {
2130 $query = $extraQuery;
2131 }
2132 $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
2133 }
2134
2135 /**
2136 * Mark this particular edit/page as patrolled
2137 */
2138 public function markpatrolled() {
2139 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUseNPPatrol, $wgUser;
2140 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2141
2142 # If we haven't been given an rc_id value, we can't do anything
2143 $rcid = (int) $wgRequest->getVal( 'rcid' );
2144 $rc = RecentChange::newFromId( $rcid );
2145 if ( is_null( $rc ) ) {
2146 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
2147 return;
2148 }
2149
2150 # It would be nice to see where the user had actually come from, but for now just guess
2151 $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
2152 $return = SpecialPage::getTitleFor( $returnto );
2153
2154 $dbw = wfGetDB( DB_MASTER );
2155 $errors = $rc->doMarkPatrolled();
2156
2157 if ( in_array( array( 'rcpatroldisabled' ), $errors ) ) {
2158 $wgOut->showErrorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
2159 return;
2160 }
2161
2162 if ( in_array( array( 'hookaborted' ), $errors ) ) {
2163 // The hook itself has handled any output
2164 return;
2165 }
2166
2167 if ( in_array( array( 'markedaspatrollederror-noautopatrol' ), $errors ) ) {
2168 $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
2169 $wgOut->addWikiMsg( 'markedaspatrollederror-noautopatrol' );
2170 $wgOut->returnToMain( false, $return );
2171 return;
2172 }
2173
2174 if ( !empty( $errors ) ) {
2175 $wgOut->showPermissionsErrorPage( $errors );
2176 return;
2177 }
2178
2179 # Inform the user
2180 $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
2181 $wgOut->addWikiMsg( 'markedaspatrolledtext', $rc->getTitle()->getPrefixedText() );
2182 $wgOut->returnToMain( false, $return );
2183 }
2184
2185 /**
2186 * User-interface handler for the "watch" action
2187 */
2188 public function watch() {
2189 global $wgUser, $wgOut;
2190 if ( $wgUser->isAnon() ) {
2191 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2192 return;
2193 }
2194 if ( wfReadOnly() ) {
2195 $wgOut->readOnlyPage();
2196 return;
2197 }
2198 if ( $this->doWatch() ) {
2199 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
2200 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2201 $wgOut->addWikiMsg( 'addedwatchtext', $this->mTitle->getPrefixedText() );
2202 }
2203 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2204 }
2205
2206 /**
2207 * Add this page to $wgUser's watchlist
2208 * @return bool true on successful watch operation
2209 */
2210 public function doWatch() {
2211 global $wgUser;
2212 if ( $wgUser->isAnon() ) {
2213 return false;
2214 }
2215 if ( wfRunHooks( 'WatchArticle', array( &$wgUser, &$this ) ) ) {
2216 $wgUser->addWatch( $this->mTitle );
2217 return wfRunHooks( 'WatchArticleComplete', array( &$wgUser, &$this ) );
2218 }
2219 return false;
2220 }
2221
2222 /**
2223 * User interface handler for the "unwatch" action.
2224 */
2225 public function unwatch() {
2226 global $wgUser, $wgOut;
2227 if ( $wgUser->isAnon() ) {
2228 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
2229 return;
2230 }
2231 if ( wfReadOnly() ) {
2232 $wgOut->readOnlyPage();
2233 return;
2234 }
2235 if ( $this->doUnwatch() ) {
2236 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
2237 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2238 $wgOut->addWikiMsg( 'removedwatchtext', $this->mTitle->getPrefixedText() );
2239 }
2240 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
2241 }
2242
2243 /**
2244 * Stop watching a page
2245 * @return bool true on successful unwatch
2246 */
2247 public function doUnwatch() {
2248 global $wgUser;
2249 if ( $wgUser->isAnon() ) {
2250 return false;
2251 }
2252 if ( wfRunHooks( 'UnwatchArticle', array( &$wgUser, &$this ) ) ) {
2253 $wgUser->removeWatch( $this->mTitle );
2254 return wfRunHooks( 'UnwatchArticleComplete', array( &$wgUser, &$this ) );
2255 }
2256 return false;
2257 }
2258
2259 /**
2260 * action=protect handler
2261 */
2262 public function protect() {
2263 $form = new ProtectionForm( $this );
2264 $form->execute();
2265 }
2266
2267 /**
2268 * action=unprotect handler (alias)
2269 */
2270 public function unprotect() {
2271 $this->protect();
2272 }
2273
2274 /**
2275 * Update the article's restriction field, and leave a log entry.
2276 *
2277 * @param $limit Array: set of restriction keys
2278 * @param $reason String
2279 * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
2280 * @param $expiry Array: per restriction type expiration
2281 * @return bool true on success
2282 */
2283 public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
2284 global $wgUser, $wgContLang;
2285
2286 $restrictionTypes = $this->mTitle->getRestrictionTypes();
2287
2288 $id = $this->mTitle->getArticleID();
2289 if ( $id <= 0 ) {
2290 wfDebug( "updateRestrictions failed: $id <= 0\n" );
2291 return false;
2292 }
2293
2294 if ( wfReadOnly() ) {
2295 wfDebug( "updateRestrictions failed: read-only\n" );
2296 return false;
2297 }
2298
2299 if ( !$this->mTitle->userCan( 'protect' ) ) {
2300 wfDebug( "updateRestrictions failed: insufficient permissions\n" );
2301 return false;
2302 }
2303
2304 if ( !$cascade ) {
2305 $cascade = false;
2306 }
2307
2308 // Take this opportunity to purge out expired restrictions
2309 Title::purgeExpiredRestrictions();
2310
2311 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
2312 # we expect a single selection, but the schema allows otherwise.
2313 $current = array();
2314 $updated = Article::flattenRestrictions( $limit );
2315 $changed = false;
2316 foreach ( $restrictionTypes as $action ) {
2317 if ( isset( $expiry[$action] ) ) {
2318 # Get current restrictions on $action
2319 $aLimits = $this->mTitle->getRestrictions( $action );
2320 $current[$action] = implode( '', $aLimits );
2321 # Are any actual restrictions being dealt with here?
2322 $aRChanged = count( $aLimits ) || !empty( $limit[$action] );
2323 # If something changed, we need to log it. Checking $aRChanged
2324 # assures that "unprotecting" a page that is not protected does
2325 # not log just because the expiry was "changed".
2326 if ( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
2327 $changed = true;
2328 }
2329 }
2330 }
2331
2332 $current = Article::flattenRestrictions( $current );
2333
2334 $changed = ( $changed || $current != $updated );
2335 $changed = $changed || ( $updated && $this->mTitle->areRestrictionsCascading() != $cascade );
2336 $protect = ( $updated != '' );
2337
2338 # If nothing's changed, do nothing
2339 if ( $changed ) {
2340 if ( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
2341
2342 $dbw = wfGetDB( DB_MASTER );
2343
2344 # Prepare a null revision to be added to the history
2345 $modified = $current != '' && $protect;
2346 if ( $protect ) {
2347 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
2348 } else {
2349 $comment_type = 'unprotectedarticle';
2350 }
2351 $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
2352
2353 # Only restrictions with the 'protect' right can cascade...
2354 # Otherwise, people who cannot normally protect can "protect" pages via transclusion
2355 $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
2356 # The schema allows multiple restrictions
2357 if ( !in_array( 'protect', $editrestriction ) && !in_array( 'sysop', $editrestriction ) )
2358 $cascade = false;
2359 $cascade_description = '';
2360 if ( $cascade ) {
2361 $cascade_description = ' [' . wfMsgForContent( 'protect-summary-cascade' ) . ']';
2362 }
2363
2364 if ( $reason )
2365 $comment .= ": $reason";
2366
2367 $editComment = $comment;
2368 $encodedExpiry = array();
2369 $protect_description = '';
2370 foreach ( $limit as $action => $restrictions ) {
2371 if ( !isset( $expiry[$action] ) )
2372 $expiry[$action] = 'infinite';
2373
2374 $encodedExpiry[$action] = Block::encodeExpiry( $expiry[$action], $dbw );
2375 if ( $restrictions != '' ) {
2376 $protect_description .= "[$action=$restrictions] (";
2377 if ( $encodedExpiry[$action] != 'infinity' ) {
2378 $protect_description .= wfMsgForContent( 'protect-expiring',
2379 $wgContLang->timeanddate( $expiry[$action], false, false ) ,
2380 $wgContLang->date( $expiry[$action], false, false ) ,
2381 $wgContLang->time( $expiry[$action], false, false ) );
2382 } else {
2383 $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
2384 }
2385 $protect_description .= ') ';
2386 }
2387 }
2388 $protect_description = trim( $protect_description );
2389
2390 if ( $protect_description && $protect )
2391 $editComment .= " ($protect_description)";
2392 if ( $cascade )
2393 $editComment .= "$cascade_description";
2394 # Update restrictions table
2395 foreach ( $limit as $action => $restrictions ) {
2396 if ( $restrictions != '' ) {
2397 $dbw->replace( 'page_restrictions', array( array( 'pr_page', 'pr_type' ) ),
2398 array( 'pr_page' => $id,
2399 'pr_type' => $action,
2400 'pr_level' => $restrictions,
2401 'pr_cascade' => ( $cascade && $action == 'edit' ) ? 1 : 0,
2402 'pr_expiry' => $encodedExpiry[$action] ), __METHOD__ );
2403 } else {
2404 $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
2405 'pr_type' => $action ), __METHOD__ );
2406 }
2407 }
2408
2409 # Insert a null revision
2410 $nullRevision = Revision::newNullRevision( $dbw, $id, $editComment, true );
2411 $nullRevId = $nullRevision->insertOn( $dbw );
2412
2413 $latest = $this->getLatest();
2414 # Update page record
2415 $dbw->update( 'page',
2416 array( /* SET */
2417 'page_touched' => $dbw->timestamp(),
2418 'page_restrictions' => '',
2419 'page_latest' => $nullRevId
2420 ), array( /* WHERE */
2421 'page_id' => $id
2422 ), 'Article::protect'
2423 );
2424
2425 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $nullRevision, $latest, $wgUser ) );
2426 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
2427
2428 # Update the protection log
2429 $log = new LogPage( 'protect' );
2430 if ( $protect ) {
2431 $params = array( $protect_description, $cascade ? 'cascade' : '' );
2432 $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason ), $params );
2433 } else {
2434 $log->addEntry( 'unprotect', $this->mTitle, $reason );
2435 }
2436
2437 } # End hook
2438 } # End "changed" check
2439
2440 return true;
2441 }
2442
2443 /**
2444 * Take an array of page restrictions and flatten it to a string
2445 * suitable for insertion into the page_restrictions field.
2446 * @param $limit Array
2447 * @return String
2448 */
2449 protected static function flattenRestrictions( $limit ) {
2450 if ( !is_array( $limit ) ) {
2451 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
2452 }
2453 $bits = array();
2454 ksort( $limit );
2455 foreach ( $limit as $action => $restrictions ) {
2456 if ( $restrictions != '' ) {
2457 $bits[] = "$action=$restrictions";
2458 }
2459 }
2460 return implode( ':', $bits );
2461 }
2462
2463 /**
2464 * Auto-generates a deletion reason
2465 * @param &$hasHistory Boolean: whether the page has a history
2466 */
2467 public function generateReason( &$hasHistory ) {
2468 global $wgContLang;
2469 $dbw = wfGetDB( DB_MASTER );
2470 // Get the last revision
2471 $rev = Revision::newFromTitle( $this->mTitle );
2472 if ( is_null( $rev ) )
2473 return false;
2474
2475 // Get the article's contents
2476 $contents = $rev->getText();
2477 $blank = false;
2478 // If the page is blank, use the text from the previous revision,
2479 // which can only be blank if there's a move/import/protect dummy revision involved
2480 if ( $contents == '' ) {
2481 $prev = $rev->getPrevious();
2482 if ( $prev ) {
2483 $contents = $prev->getText();
2484 $blank = true;
2485 }
2486 }
2487
2488 // Find out if there was only one contributor
2489 // Only scan the last 20 revisions
2490 $res = $dbw->select( 'revision', 'rev_user_text',
2491 array( 'rev_page' => $this->getID(), $dbw->bitAnd( 'rev_deleted', Revision::DELETED_USER ) . ' = 0' ),
2492 __METHOD__,
2493 array( 'LIMIT' => 20 )
2494 );
2495 if ( $res === false )
2496 // This page has no revisions, which is very weird
2497 return false;
2498
2499 $hasHistory = ( $res->numRows() > 1 );
2500 $row = $dbw->fetchObject( $res );
2501 $onlyAuthor = $row->rev_user_text;
2502 // Try to find a second contributor
2503 foreach ( $res as $row ) {
2504 if ( $row->rev_user_text != $onlyAuthor ) {
2505 $onlyAuthor = false;
2506 break;
2507 }
2508 }
2509 $dbw->freeResult( $res );
2510
2511 // Generate the summary with a '$1' placeholder
2512 if ( $blank ) {
2513 // The current revision is blank and the one before is also
2514 // blank. It's just not our lucky day
2515 $reason = wfMsgForContent( 'exbeforeblank', '$1' );
2516 } else {
2517 if ( $onlyAuthor )
2518 $reason = wfMsgForContent( 'excontentauthor', '$1', $onlyAuthor );
2519 else
2520 $reason = wfMsgForContent( 'excontent', '$1' );
2521 }
2522
2523 if ( $reason == '-' ) {
2524 // Allow these UI messages to be blanked out cleanly
2525 return '';
2526 }
2527
2528 // Replace newlines with spaces to prevent uglyness
2529 $contents = preg_replace( "/[\n\r]/", ' ', $contents );
2530 // Calculate the maximum amount of chars to get
2531 // Max content length = max comment length - length of the comment (excl. $1) - '...'
2532 $maxLength = 255 - ( strlen( $reason ) - 2 ) - 3;
2533 $contents = $wgContLang->truncate( $contents, $maxLength );
2534 // Remove possible unfinished links
2535 $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
2536 // Now replace the '$1' placeholder
2537 $reason = str_replace( '$1', $contents, $reason );
2538 return $reason;
2539 }
2540
2541
2542 /*
2543 * UI entry point for page deletion
2544 */
2545 public function delete() {
2546 global $wgUser, $wgOut, $wgRequest;
2547
2548 $confirm = $wgRequest->wasPosted() &&
2549 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
2550
2551 $this->DeleteReasonList = $wgRequest->getText( 'wpDeleteReasonList', 'other' );
2552 $this->DeleteReason = $wgRequest->getText( 'wpReason' );
2553
2554 $reason = $this->DeleteReasonList;
2555
2556 if ( $reason != 'other' && $this->DeleteReason != '' ) {
2557 // Entry from drop down menu + additional comment
2558 $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
2559 } elseif ( $reason == 'other' ) {
2560 $reason = $this->DeleteReason;
2561 }
2562 # Flag to hide all contents of the archived revisions
2563 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
2564
2565 # This code desperately needs to be totally rewritten
2566
2567 # Read-only check...
2568 if ( wfReadOnly() ) {
2569 $wgOut->readOnlyPage();
2570 return;
2571 }
2572
2573 # Check permissions
2574 $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
2575
2576 if ( count( $permission_errors ) > 0 ) {
2577 $wgOut->showPermissionsErrorPage( $permission_errors );
2578 return;
2579 }
2580
2581 $wgOut->setPagetitle( wfMsg( 'delete-confirm', $this->mTitle->getPrefixedText() ) );
2582
2583 # Better double-check that it hasn't been deleted yet!
2584 $dbw = wfGetDB( DB_MASTER );
2585 $conds = $this->mTitle->pageCond();
2586 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
2587 if ( $latest === false ) {
2588 $wgOut->showFatalError(
2589 Html::rawElement(
2590 'div',
2591 array( 'class' => 'error mw-error-cannotdelete' ),
2592 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2593 )
2594 );
2595 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2596 LogEventsList::showLogExtract(
2597 $wgOut,
2598 'delete',
2599 $this->mTitle->getPrefixedText()
2600 );
2601 return;
2602 }
2603
2604 # Hack for big sites
2605 $bigHistory = $this->isBigDeletion();
2606 if ( $bigHistory && !$this->mTitle->userCan( 'bigdelete' ) ) {
2607 global $wgLang, $wgDeleteRevisionsLimit;
2608 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2609 array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2610 return;
2611 }
2612
2613 if ( $confirm ) {
2614 $this->doDelete( $reason, $suppress );
2615 if ( $wgRequest->getCheck( 'wpWatch' ) && $wgUser->isLoggedIn() ) {
2616 $this->doWatch();
2617 } elseif ( $this->mTitle->userIsWatching() ) {
2618 $this->doUnwatch();
2619 }
2620 return;
2621 }
2622
2623 // Generate deletion reason
2624 $hasHistory = false;
2625 if ( !$reason ) $reason = $this->generateReason( $hasHistory );
2626
2627 // If the page has a history, insert a warning
2628 if ( $hasHistory && !$confirm ) {
2629 global $wgLang;
2630 $skin = $wgUser->getSkin();
2631 $revisions = $this->estimateRevisionCount();
2632 $wgOut->addHTML( '<strong class="mw-delete-warning-revisions">' .
2633 wfMsgExt( 'historywarning', array( 'parseinline' ), $wgLang->formatNum( $revisions ) ) .
2634 wfMsgHtml( 'word-separator' ) . $skin->historyLink() .
2635 '</strong>'
2636 );
2637 if ( $bigHistory ) {
2638 global $wgDeleteRevisionsLimit;
2639 $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
2640 array( 'delete-warning-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ) );
2641 }
2642 }
2643
2644 return $this->confirmDelete( $reason );
2645 }
2646
2647 /**
2648 * @return bool whether or not the page surpasses $wgDeleteRevisionsLimit revisions
2649 */
2650 public function isBigDeletion() {
2651 global $wgDeleteRevisionsLimit;
2652 if ( $wgDeleteRevisionsLimit ) {
2653 $revCount = $this->estimateRevisionCount();
2654 return $revCount > $wgDeleteRevisionsLimit;
2655 }
2656 return false;
2657 }
2658
2659 /**
2660 * @return int approximate revision count
2661 */
2662 public function estimateRevisionCount() {
2663 $dbr = wfGetDB( DB_SLAVE );
2664 // For an exact count...
2665 // return $dbr->selectField( 'revision', 'COUNT(*)',
2666 // array( 'rev_page' => $this->getId() ), __METHOD__ );
2667 return $dbr->estimateRowCount( 'revision', '*',
2668 array( 'rev_page' => $this->getId() ), __METHOD__ );
2669 }
2670
2671 /**
2672 * Get the last N authors
2673 * @param $num Integer: number of revisions to get
2674 * @param $revLatest String: the latest rev_id, selected from the master (optional)
2675 * @return array Array of authors, duplicates not removed
2676 */
2677 public function getLastNAuthors( $num, $revLatest = 0 ) {
2678 wfProfileIn( __METHOD__ );
2679 // First try the slave
2680 // If that doesn't have the latest revision, try the master
2681 $continue = 2;
2682 $db = wfGetDB( DB_SLAVE );
2683 do {
2684 $res = $db->select( array( 'page', 'revision' ),
2685 array( 'rev_id', 'rev_user_text' ),
2686 array(
2687 'page_namespace' => $this->mTitle->getNamespace(),
2688 'page_title' => $this->mTitle->getDBkey(),
2689 'rev_page = page_id'
2690 ), __METHOD__, $this->getSelectOptions( array(
2691 'ORDER BY' => 'rev_timestamp DESC',
2692 'LIMIT' => $num
2693 ) )
2694 );
2695 if ( !$res ) {
2696 wfProfileOut( __METHOD__ );
2697 return array();
2698 }
2699 $row = $db->fetchObject( $res );
2700 if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
2701 $db = wfGetDB( DB_MASTER );
2702 $continue--;
2703 } else {
2704 $continue = 0;
2705 }
2706 } while ( $continue );
2707
2708 $authors = array( $row->rev_user_text );
2709 while ( $row = $db->fetchObject( $res ) ) {
2710 $authors[] = $row->rev_user_text;
2711 }
2712 wfProfileOut( __METHOD__ );
2713 return $authors;
2714 }
2715
2716 /**
2717 * Output deletion confirmation dialog
2718 * @param $reason String: prefilled reason
2719 */
2720 public function confirmDelete( $reason ) {
2721 global $wgOut, $wgUser;
2722
2723 wfDebug( "Article::confirmDelete\n" );
2724
2725 $deleteBackLink = $wgUser->getSkin()->link(
2726 $this->mTitle,
2727 null,
2728 array(),
2729 array(),
2730 array( 'known', 'noclasses' )
2731 );
2732 $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $deleteBackLink ) );
2733 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2734 $wgOut->addWikiMsg( 'confirmdeletetext' );
2735
2736 wfRunHooks( 'ArticleConfirmDelete', array( $this, $wgOut, &$reason ) );
2737
2738 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
2739 $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
2740 <td></td>
2741 <td class='mw-input'><strong>" .
2742 Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
2743 'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
2744 "</strong></td>
2745 </tr>";
2746 } else {
2747 $suppress = '';
2748 }
2749 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching();
2750
2751 $form = Xml::openElement( 'form', array( 'method' => 'post',
2752 'action' => $this->mTitle->getLocalURL( 'action=delete' ), 'id' => 'deleteconfirm' ) ) .
2753 Xml::openElement( 'fieldset', array( 'id' => 'mw-delete-table' ) ) .
2754 Xml::tags( 'legend', null, wfMsgExt( 'delete-legend', array( 'parsemag', 'escapenoentities' ) ) ) .
2755 Xml::openElement( 'table', array( 'id' => 'mw-deleteconfirm-table' ) ) .
2756 "<tr id=\"wpDeleteReasonListRow\">
2757 <td class='mw-label'>" .
2758 Xml::label( wfMsg( 'deletecomment' ), 'wpDeleteReasonList' ) .
2759 "</td>
2760 <td class='mw-input'>" .
2761 Xml::listDropDown( 'wpDeleteReasonList',
2762 wfMsgForContent( 'deletereason-dropdown' ),
2763 wfMsgForContent( 'deletereasonotherlist' ), '', 'wpReasonDropDown', 1 ) .
2764 "</td>
2765 </tr>
2766 <tr id=\"wpDeleteReasonRow\">
2767 <td class='mw-label'>" .
2768 Xml::label( wfMsg( 'deleteotherreason' ), 'wpReason' ) .
2769 "</td>
2770 <td class='mw-input'>" .
2771 Html::input( 'wpReason', $reason, 'text', array(
2772 'size' => '60',
2773 'maxlength' => '255',
2774 'tabindex' => '2',
2775 'id' => 'wpReason',
2776 'autofocus'
2777 ) ) .
2778 "</td>
2779 </tr>";
2780 # Dissalow watching is user is not logged in
2781 if ( $wgUser->isLoggedIn() ) {
2782 $form .= "
2783 <tr>
2784 <td></td>
2785 <td class='mw-input'>" .
2786 Xml::checkLabel( wfMsg( 'watchthis' ),
2787 'wpWatch', 'wpWatch', $checkWatch, array( 'tabindex' => '3' ) ) .
2788 "</td>
2789 </tr>";
2790 }
2791 $form .= "
2792 $suppress
2793 <tr>
2794 <td></td>
2795 <td class='mw-submit'>" .
2796 Xml::submitButton( wfMsg( 'deletepage' ),
2797 array( 'name' => 'wpConfirmB', 'id' => 'wpConfirmB', 'tabindex' => '5' ) ) .
2798 "</td>
2799 </tr>" .
2800 Xml::closeElement( 'table' ) .
2801 Xml::closeElement( 'fieldset' ) .
2802 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
2803 Xml::closeElement( 'form' );
2804
2805 if ( $wgUser->isAllowed( 'editinterface' ) ) {
2806 $skin = $wgUser->getSkin();
2807 $title = Title::makeTitle( NS_MEDIAWIKI, 'Deletereason-dropdown' );
2808 $link = $skin->link(
2809 $title,
2810 wfMsgHtml( 'delete-edit-reasonlist' ),
2811 array(),
2812 array( 'action' => 'edit' )
2813 );
2814 $form .= '<p class="mw-delete-editreasons">' . $link . '</p>';
2815 }
2816
2817 $wgOut->addHTML( $form );
2818 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2819 LogEventsList::showLogExtract(
2820 $wgOut,
2821 'delete',
2822 $this->mTitle->getPrefixedText()
2823 );
2824 }
2825
2826 /**
2827 * Perform a deletion and output success or failure messages
2828 */
2829 public function doDelete( $reason, $suppress = false ) {
2830 global $wgOut, $wgUser;
2831 $id = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2832
2833 $error = '';
2834 if ( wfRunHooks( 'ArticleDelete', array( &$this, &$wgUser, &$reason, &$error ) ) ) {
2835 if ( $this->doDeleteArticle( $reason, $suppress, $id ) ) {
2836 $deleted = $this->mTitle->getPrefixedText();
2837
2838 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2839 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2840
2841 $loglink = '[[Special:Log/delete|' . wfMsgNoTrans( 'deletionlog' ) . ']]';
2842
2843 $wgOut->addWikiMsg( 'deletedtext', $deleted, $loglink );
2844 $wgOut->returnToMain( false );
2845 wfRunHooks( 'ArticleDeleteComplete', array( &$this, &$wgUser, $reason, $id ) );
2846 }
2847 } else {
2848 if ( $error == '' ) {
2849 $wgOut->showFatalError(
2850 Html::rawElement(
2851 'div',
2852 array( 'class' => 'error mw-error-cannotdelete' ),
2853 wfMsgExt( 'cannotdelete', array( 'parse' ), $this->mTitle->getPrefixedText() )
2854 )
2855 );
2856 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
2857 LogEventsList::showLogExtract(
2858 $wgOut,
2859 'delete',
2860 $this->mTitle->getPrefixedText()
2861 );
2862 } else {
2863 $wgOut->showFatalError( $error );
2864 }
2865 }
2866 }
2867
2868 /**
2869 * Back-end article deletion
2870 * Deletes the article with database consistency, writes logs, purges caches
2871 * Returns success
2872 */
2873 public function doDeleteArticle( $reason, $suppress = false, $id = 0, $commit = true ) {
2874 global $wgUseSquid, $wgDeferredUpdateList;
2875 global $wgUseTrackbacks;
2876
2877 wfDebug( __METHOD__ . "\n" );
2878
2879 $dbw = wfGetDB( DB_MASTER );
2880 $ns = $this->mTitle->getNamespace();
2881 $t = $this->mTitle->getDBkey();
2882 $id = $id ? $id : $this->mTitle->getArticleID( GAID_FOR_UPDATE );
2883
2884 if ( $t == '' || $id == 0 ) {
2885 return false;
2886 }
2887
2888 $u = new SiteStatsUpdate( 0, 1, - (int)$this->isCountable( $this->getRawText() ), -1 );
2889 array_push( $wgDeferredUpdateList, $u );
2890
2891 // Bitfields to further suppress the content
2892 if ( $suppress ) {
2893 $bitfield = 0;
2894 // This should be 15...
2895 $bitfield |= Revision::DELETED_TEXT;
2896 $bitfield |= Revision::DELETED_COMMENT;
2897 $bitfield |= Revision::DELETED_USER;
2898 $bitfield |= Revision::DELETED_RESTRICTED;
2899 } else {
2900 $bitfield = 'rev_deleted';
2901 }
2902
2903 $dbw->begin();
2904 // For now, shunt the revision data into the archive table.
2905 // Text is *not* removed from the text table; bulk storage
2906 // is left intact to avoid breaking block-compression or
2907 // immutable storage schemes.
2908 //
2909 // For backwards compatibility, note that some older archive
2910 // table entries will have ar_text and ar_flags fields still.
2911 //
2912 // In the future, we may keep revisions and mark them with
2913 // the rev_deleted field, which is reserved for this purpose.
2914 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2915 array(
2916 'ar_namespace' => 'page_namespace',
2917 'ar_title' => 'page_title',
2918 'ar_comment' => 'rev_comment',
2919 'ar_user' => 'rev_user',
2920 'ar_user_text' => 'rev_user_text',
2921 'ar_timestamp' => 'rev_timestamp',
2922 'ar_minor_edit' => 'rev_minor_edit',
2923 'ar_rev_id' => 'rev_id',
2924 'ar_text_id' => 'rev_text_id',
2925 'ar_text' => '\'\'', // Be explicit to appease
2926 'ar_flags' => '\'\'', // MySQL's "strict mode"...
2927 'ar_len' => 'rev_len',
2928 'ar_page_id' => 'page_id',
2929 'ar_deleted' => $bitfield
2930 ), array(
2931 'page_id' => $id,
2932 'page_id = rev_page'
2933 ), __METHOD__
2934 );
2935
2936 # Delete restrictions for it
2937 $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
2938
2939 # Now that it's safely backed up, delete it
2940 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__ );
2941 $ok = ( $dbw->affectedRows() > 0 ); // getArticleId() uses slave, could be laggy
2942 if ( !$ok ) {
2943 $dbw->rollback();
2944 return false;
2945 }
2946
2947 # Fix category table counts
2948 $cats = array();
2949 $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
2950 foreach ( $res as $row ) {
2951 $cats [] = $row->cl_to;
2952 }
2953 $this->updateCategoryCounts( array(), $cats );
2954
2955 # If using cascading deletes, we can skip some explicit deletes
2956 if ( !$dbw->cascadingDeletes() ) {
2957 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__ );
2958
2959 if ( $wgUseTrackbacks )
2960 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__ );
2961
2962 # Delete outgoing links
2963 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2964 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2965 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2966 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2967 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2968 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2969 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2970 }
2971
2972 # If using cleanup triggers, we can skip some manual deletes
2973 if ( !$dbw->cleanupTriggers() ) {
2974 # Clean up recentchanges entries...
2975 $dbw->delete( 'recentchanges',
2976 array( 'rc_type != ' . RC_LOG,
2977 'rc_namespace' => $this->mTitle->getNamespace(),
2978 'rc_title' => $this->mTitle->getDBkey() ),
2979 __METHOD__ );
2980 $dbw->delete( 'recentchanges',
2981 array( 'rc_type != ' . RC_LOG, 'rc_cur_id' => $id ),
2982 __METHOD__ );
2983 }
2984
2985 # Clear caches
2986 Article::onArticleDelete( $this->mTitle );
2987
2988 # Clear the cached article id so the interface doesn't act like we exist
2989 $this->mTitle->resetArticleID( 0 );
2990
2991 # Log the deletion, if the page was suppressed, log it at Oversight instead
2992 $logtype = $suppress ? 'suppress' : 'delete';
2993 $log = new LogPage( $logtype );
2994
2995 # Make sure logging got through
2996 $log->addEntry( 'delete', $this->mTitle, $reason, array() );
2997
2998 if ( $commit ) {
2999 $dbw->commit();
3000 }
3001
3002 return true;
3003 }
3004
3005 /**
3006 * Roll back the most recent consecutive set of edits to a page
3007 * from the same user; fails if there are no eligible edits to
3008 * roll back to, e.g. user is the sole contributor. This function
3009 * performs permissions checks on $wgUser, then calls commitRollback()
3010 * to do the dirty work
3011 *
3012 * @param $fromP String: Name of the user whose edits to rollback.
3013 * @param $summary String: Custom summary. Set to default summary if empty.
3014 * @param $token String: Rollback token.
3015 * @param $bot Boolean: If true, mark all reverted edits as bot.
3016 *
3017 * @param $resultDetails Array: contains result-specific array of additional values
3018 * 'alreadyrolled' : 'current' (rev)
3019 * success : 'summary' (str), 'current' (rev), 'target' (rev)
3020 *
3021 * @return array of errors, each error formatted as
3022 * array(messagekey, param1, param2, ...).
3023 * On success, the array is empty. This array can also be passed to
3024 * OutputPage::showPermissionsErrorPage().
3025 */
3026 public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
3027 global $wgUser;
3028 $resultDetails = null;
3029
3030 # Check permissions
3031 $editErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser );
3032 $rollbackErrors = $this->mTitle->getUserPermissionsErrors( 'rollback', $wgUser );
3033 $errors = array_merge( $editErrors, wfArrayDiff2( $rollbackErrors, $editErrors ) );
3034
3035 if ( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
3036 $errors[] = array( 'sessionfailure' );
3037
3038 if ( $wgUser->pingLimiter( 'rollback' ) || $wgUser->pingLimiter() ) {
3039 $errors[] = array( 'actionthrottledtext' );
3040 }
3041 # If there were errors, bail out now
3042 if ( !empty( $errors ) )
3043 return $errors;
3044
3045 return $this->commitRollback( $fromP, $summary, $bot, $resultDetails );
3046 }
3047
3048 /**
3049 * Backend implementation of doRollback(), please refer there for parameter
3050 * and return value documentation
3051 *
3052 * NOTE: This function does NOT check ANY permissions, it just commits the
3053 * rollback to the DB Therefore, you should only call this function direct-
3054 * ly if you want to use custom permissions checks. If you don't, use
3055 * doRollback() instead.
3056 */
3057 public function commitRollback( $fromP, $summary, $bot, &$resultDetails ) {
3058 global $wgUseRCPatrol, $wgUser, $wgLang;
3059 $dbw = wfGetDB( DB_MASTER );
3060
3061 if ( wfReadOnly() ) {
3062 return array( array( 'readonlytext' ) );
3063 }
3064
3065 # Get the last editor
3066 $current = Revision::newFromTitle( $this->mTitle );
3067 if ( is_null( $current ) ) {
3068 # Something wrong... no page?
3069 return array( array( 'notanarticle' ) );
3070 }
3071
3072 $from = str_replace( '_', ' ', $fromP );
3073 # User name given should match up with the top revision.
3074 # If the user was deleted then $from should be empty.
3075 if ( $from != $current->getUserText() ) {
3076 $resultDetails = array( 'current' => $current );
3077 return array( array( 'alreadyrolled',
3078 htmlspecialchars( $this->mTitle->getPrefixedText() ),
3079 htmlspecialchars( $fromP ),
3080 htmlspecialchars( $current->getUserText() )
3081 ) );
3082 }
3083
3084 # Get the last edit not by this guy...
3085 # Note: these may not be public values
3086 $user = intval( $current->getRawUser() );
3087 $user_text = $dbw->addQuotes( $current->getRawUserText() );
3088 $s = $dbw->selectRow( 'revision',
3089 array( 'rev_id', 'rev_timestamp', 'rev_deleted' ),
3090 array( 'rev_page' => $current->getPage(),
3091 "rev_user != {$user} OR rev_user_text != {$user_text}"
3092 ), __METHOD__,
3093 array( 'USE INDEX' => 'page_timestamp',
3094 'ORDER BY' => 'rev_timestamp DESC' )
3095 );
3096 if ( $s === false ) {
3097 # No one else ever edited this page
3098 return array( array( 'cantrollback' ) );
3099 } else if ( $s->rev_deleted & REVISION::DELETED_TEXT || $s->rev_deleted & REVISION::DELETED_USER ) {
3100 # Only admins can see this text
3101 return array( array( 'notvisiblerev' ) );
3102 }
3103
3104 $set = array();
3105 if ( $bot && $wgUser->isAllowed( 'markbotedits' ) ) {
3106 # Mark all reverted edits as bot
3107 $set['rc_bot'] = 1;
3108 }
3109 if ( $wgUseRCPatrol ) {
3110 # Mark all reverted edits as patrolled
3111 $set['rc_patrolled'] = 1;
3112 }
3113
3114 if ( count( $set ) ) {
3115 $dbw->update( 'recentchanges', $set,
3116 array( /* WHERE */
3117 'rc_cur_id' => $current->getPage(),
3118 'rc_user_text' => $current->getUserText(),
3119 "rc_timestamp > '{$s->rev_timestamp}'",
3120 ), __METHOD__
3121 );
3122 }
3123
3124 # Generate the edit summary if necessary
3125 $target = Revision::newFromId( $s->rev_id );
3126 if ( empty( $summary ) ) {
3127 if ( $from == '' ) { // no public user name
3128 $summary = wfMsgForContent( 'revertpage-nouser' );
3129 } else {
3130 $summary = wfMsgForContent( 'revertpage' );
3131 }
3132 }
3133
3134 # Allow the custom summary to use the same args as the default message
3135 $args = array(
3136 $target->getUserText(), $from, $s->rev_id,
3137 $wgLang->timeanddate( wfTimestamp( TS_MW, $s->rev_timestamp ), true ),
3138 $current->getId(), $wgLang->timeanddate( $current->getTimestamp() )
3139 );
3140 $summary = wfMsgReplaceArgs( $summary, $args );
3141
3142 # Save
3143 $flags = EDIT_UPDATE;
3144
3145 if ( $wgUser->isAllowed( 'minoredit' ) )
3146 $flags |= EDIT_MINOR;
3147
3148 if ( $bot && ( $wgUser->isAllowed( 'markbotedits' ) || $wgUser->isAllowed( 'bot' ) ) )
3149 $flags |= EDIT_FORCE_BOT;
3150 # Actually store the edit
3151 $status = $this->doEdit( $target->getText(), $summary, $flags, $target->getId() );
3152 if ( !empty( $status->value['revision'] ) ) {
3153 $revId = $status->value['revision']->getId();
3154 } else {
3155 $revId = false;
3156 }
3157
3158 wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
3159
3160 $resultDetails = array(
3161 'summary' => $summary,
3162 'current' => $current,
3163 'target' => $target,
3164 'newid' => $revId
3165 );
3166 return array();
3167 }
3168
3169 /**
3170 * User interface for rollback operations
3171 */
3172 public function rollback() {
3173 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
3174 $details = null;
3175
3176 $result = $this->doRollback(
3177 $wgRequest->getVal( 'from' ),
3178 $wgRequest->getText( 'summary' ),
3179 $wgRequest->getVal( 'token' ),
3180 $wgRequest->getBool( 'bot' ),
3181 $details
3182 );
3183
3184 if ( in_array( array( 'actionthrottledtext' ), $result ) ) {
3185 $wgOut->rateLimited();
3186 return;
3187 }
3188 if ( isset( $result[0][0] ) && ( $result[0][0] == 'alreadyrolled' || $result[0][0] == 'cantrollback' ) ) {
3189 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
3190 $errArray = $result[0];
3191 $errMsg = array_shift( $errArray );
3192 $wgOut->addWikiMsgArray( $errMsg, $errArray );
3193 if ( isset( $details['current'] ) ) {
3194 $current = $details['current'];
3195 if ( $current->getComment() != '' ) {
3196 $wgOut->addWikiMsgArray( 'editcomment', array(
3197 $wgUser->getSkin()->formatComment( $current->getComment() ) ), array( 'replaceafter' ) );
3198 }
3199 }
3200 return;
3201 }
3202 # Display permissions errors before read-only message -- there's no
3203 # point in misleading the user into thinking the inability to rollback
3204 # is only temporary.
3205 if ( !empty( $result ) && $result !== array( array( 'readonlytext' ) ) ) {
3206 # array_diff is completely broken for arrays of arrays, sigh. Re-
3207 # move any 'readonlytext' error manually.
3208 $out = array();
3209 foreach ( $result as $error ) {
3210 if ( $error != array( 'readonlytext' ) ) {
3211 $out [] = $error;
3212 }
3213 }
3214 $wgOut->showPermissionsErrorPage( $out );
3215 return;
3216 }
3217 if ( $result == array( array( 'readonlytext' ) ) ) {
3218 $wgOut->readOnlyPage();
3219 return;
3220 }
3221
3222 $current = $details['current'];
3223 $target = $details['target'];
3224 $newId = $details['newid'];
3225 $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
3226 $wgOut->setRobotPolicy( 'noindex,nofollow' );
3227 if ( $current->getUserText() === '' ) {
3228 $old = wfMsg( 'rev-deleted-user' );
3229 } else {
3230 $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
3231 . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
3232 }
3233 $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
3234 . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
3235 $wgOut->addHTML( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
3236 $wgOut->returnToMain( false, $this->mTitle );
3237
3238 if ( !$wgRequest->getBool( 'hidediff', false ) && !$wgUser->getBoolOption( 'norollbackdiff', false ) ) {
3239 $de = new DifferenceEngine( $this->mTitle, $current->getId(), $newId, false, true );
3240 $de->showDiff( '', '' );
3241 }
3242 }
3243
3244
3245 /**
3246 * Do standard deferred updates after page view
3247 */
3248 public function viewUpdates() {
3249 global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
3250 if ( wfReadOnly() ) {
3251 return;
3252 }
3253 # Don't update page view counters on views from bot users (bug 14044)
3254 if ( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) && $this->getID() ) {
3255 Article::incViewCount( $this->getID() );
3256 $u = new SiteStatsUpdate( 1, 0, 0 );
3257 array_push( $wgDeferredUpdateList, $u );
3258 }
3259 # Update newtalk / watchlist notification status
3260 $wgUser->clearNotification( $this->mTitle );
3261 }
3262
3263 /**
3264 * Prepare text which is about to be saved.
3265 * Returns a stdclass with source, pst and output members
3266 */
3267 public function prepareTextForEdit( $text, $revid = null ) {
3268 if ( $this->mPreparedEdit && $this->mPreparedEdit->newText == $text && $this->mPreparedEdit->revid == $revid ) {
3269 // Already prepared
3270 return $this->mPreparedEdit;
3271 }
3272 global $wgParser;
3273 $edit = (object)array();
3274 $edit->revid = $revid;
3275 $edit->newText = $text;
3276 $edit->pst = $this->preSaveTransform( $text );
3277 $options = $this->getParserOptions();
3278 $edit->output = $wgParser->parse( $edit->pst, $this->mTitle, $options, true, true, $revid );
3279 $edit->oldText = $this->getContent();
3280 $this->mPreparedEdit = $edit;
3281 return $edit;
3282 }
3283
3284 /**
3285 * Do standard deferred updates after page edit.
3286 * Update links tables, site stats, search index and message cache.
3287 * Purges pages that include this page if the text was changed here.
3288 * Every 100th edit, prune the recent changes table.
3289 *
3290 * @private
3291 * @param $text New text of the article
3292 * @param $summary Edit summary
3293 * @param $minoredit Minor edit
3294 * @param $timestamp_of_pagechange Timestamp associated with the page change
3295 * @param $newid rev_id value of the new revision
3296 * @param $changed Whether or not the content actually changed
3297 */
3298 public function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
3299 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgEnableParserCache;
3300
3301 wfProfileIn( __METHOD__ );
3302
3303 # Parse the text
3304 # Be careful not to double-PST: $text is usually already PST-ed once
3305 if ( !$this->mPreparedEdit || $this->mPreparedEdit->output->getFlag( 'vary-revision' ) ) {
3306 wfDebug( __METHOD__ . ": No prepared edit or vary-revision is set...\n" );
3307 $editInfo = $this->prepareTextForEdit( $text, $newid );
3308 } else {
3309 wfDebug( __METHOD__ . ": No vary-revision, using prepared edit...\n" );
3310 $editInfo = $this->mPreparedEdit;
3311 }
3312
3313 # Save it to the parser cache
3314 if ( $wgEnableParserCache ) {
3315 $popts = $this->getParserOptions();
3316 $parserCache = ParserCache::singleton();
3317 $parserCache->save( $editInfo->output, $this, $popts );
3318 }
3319
3320 # Update the links tables
3321 $u = new LinksUpdate( $this->mTitle, $editInfo->output );
3322 $u->doUpdate();
3323
3324 wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
3325
3326 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
3327 if ( 0 == mt_rand( 0, 99 ) ) {
3328 // Flush old entries from the `recentchanges` table; we do this on
3329 // random requests so as to avoid an increase in writes for no good reason
3330 global $wgRCMaxAge;
3331 $dbw = wfGetDB( DB_MASTER );
3332 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
3333 $recentchanges = $dbw->tableName( 'recentchanges' );
3334 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
3335 $dbw->query( $sql );
3336 }
3337 }
3338
3339 $id = $this->getID();
3340 $title = $this->mTitle->getPrefixedDBkey();
3341 $shortTitle = $this->mTitle->getDBkey();
3342
3343 if ( 0 == $id ) {
3344 wfProfileOut( __METHOD__ );
3345 return;
3346 }
3347
3348 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
3349 array_push( $wgDeferredUpdateList, $u );
3350 $u = new SearchUpdate( $id, $title, $text );
3351 array_push( $wgDeferredUpdateList, $u );
3352
3353 # If this is another user's talk page, update newtalk
3354 # Don't do this if $changed = false otherwise some idiot can null-edit a
3355 # load of user talk pages and piss people off, nor if it's a minor edit
3356 # by a properly-flagged bot.
3357 if ( $this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getTitleKey() && $changed
3358 && !( $minoredit && $wgUser->isAllowed( 'nominornewtalk' ) ) ) {
3359 if ( wfRunHooks( 'ArticleEditUpdateNewTalk', array( &$this ) ) ) {
3360 $other = User::newFromName( $shortTitle, false );
3361 if ( !$other ) {
3362 wfDebug( __METHOD__ . ": invalid username\n" );
3363 } elseif ( User::isIP( $shortTitle ) ) {
3364 // An anonymous user
3365 $other->setNewtalk( true );
3366 } elseif ( $other->isLoggedIn() ) {
3367 $other->setNewtalk( true );
3368 } else {
3369 wfDebug( __METHOD__ . ": don't need to notify a nonexistent user\n" );
3370 }
3371 }
3372 }
3373
3374 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3375 $wgMessageCache->replace( $shortTitle, $text );
3376 }
3377
3378 wfProfileOut( __METHOD__ );
3379 }
3380
3381 /**
3382 * Perform article updates on a special page creation.
3383 *
3384 * @param $rev Revision object
3385 *
3386 * @todo This is a shitty interface function. Kill it and replace the
3387 * other shitty functions like editUpdates and such so it's not needed
3388 * anymore.
3389 */
3390 public function createUpdates( $rev ) {
3391 $this->mGoodAdjustment = $this->isCountable( $rev->getText() );
3392 $this->mTotalAdjustment = 1;
3393 $this->editUpdates( $rev->getText(), $rev->getComment(),
3394 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
3395 }
3396
3397 /**
3398 * Generate the navigation links when browsing through an article revisions
3399 * It shows the information as:
3400 * Revision as of \<date\>; view current revision
3401 * \<- Previous version | Next Version -\>
3402 *
3403 * @param $oldid String: revision ID of this article revision
3404 */
3405 public function setOldSubtitle( $oldid = 0 ) {
3406 global $wgLang, $wgOut, $wgUser, $wgRequest;
3407
3408 if ( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
3409 return;
3410 }
3411
3412 $unhide = $wgRequest->getInt( 'unhide' ) == 1 &&
3413 $wgUser->matchEditToken( $wgRequest->getVal( 'token' ), $oldid );
3414 # Cascade unhide param in links for easy deletion browsing
3415 $extraParams = array();
3416 if ( $wgRequest->getVal( 'unhide' ) ) {
3417 $extraParams['unhide'] = 1;
3418 }
3419 $revision = Revision::newFromId( $oldid );
3420
3421 $current = ( $oldid == $this->mLatest );
3422 $td = $wgLang->timeanddate( $this->mTimestamp, true );
3423 $tddate = $wgLang->date( $this->mTimestamp, true );
3424 $tdtime = $wgLang->time( $this->mTimestamp, true );
3425 $sk = $wgUser->getSkin();
3426 $lnk = $current
3427 ? wfMsgHtml( 'currentrevisionlink' )
3428 : $sk->link(
3429 $this->mTitle,
3430 wfMsgHtml( 'currentrevisionlink' ),
3431 array(),
3432 $extraParams,
3433 array( 'known', 'noclasses' )
3434 );
3435 $curdiff = $current
3436 ? wfMsgHtml( 'diff' )
3437 : $sk->link(
3438 $this->mTitle,
3439 wfMsgHtml( 'diff' ),
3440 array(),
3441 array(
3442 'diff' => 'cur',
3443 'oldid' => $oldid
3444 ) + $extraParams,
3445 array( 'known', 'noclasses' )
3446 );
3447 $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
3448 $prevlink = $prev
3449 ? $sk->link(
3450 $this->mTitle,
3451 wfMsgHtml( 'previousrevision' ),
3452 array(),
3453 array(
3454 'direction' => 'prev',
3455 'oldid' => $oldid
3456 ) + $extraParams,
3457 array( 'known', 'noclasses' )
3458 )
3459 : wfMsgHtml( 'previousrevision' );
3460 $prevdiff = $prev
3461 ? $sk->link(
3462 $this->mTitle,
3463 wfMsgHtml( 'diff' ),
3464 array(),
3465 array(
3466 'diff' => 'prev',
3467 'oldid' => $oldid
3468 ) + $extraParams,
3469 array( 'known', 'noclasses' )
3470 )
3471 : wfMsgHtml( 'diff' );
3472 $nextlink = $current
3473 ? wfMsgHtml( 'nextrevision' )
3474 : $sk->link(
3475 $this->mTitle,
3476 wfMsgHtml( 'nextrevision' ),
3477 array(),
3478 array(
3479 'direction' => 'next',
3480 'oldid' => $oldid
3481 ) + $extraParams,
3482 array( 'known', 'noclasses' )
3483 );
3484 $nextdiff = $current
3485 ? wfMsgHtml( 'diff' )
3486 : $sk->link(
3487 $this->mTitle,
3488 wfMsgHtml( 'diff' ),
3489 array(),
3490 array(
3491 'diff' => 'next',
3492 'oldid' => $oldid
3493 ) + $extraParams,
3494 array( 'known', 'noclasses' )
3495 );
3496
3497 $cdel = '';
3498 // User can delete revisions or view deleted revisions...
3499 $canHide = $wgUser->isAllowed( 'deleterevision' );
3500 if ( $canHide || ( $revision->getVisibility() && $wgUser->isAllowed( 'deletedhistory' ) ) ) {
3501 if ( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
3502 $cdel = $sk->revDeleteLinkDisabled( $canHide ); // rev was hidden from Sysops
3503 } else {
3504 $query = array(
3505 'type' => 'revision',
3506 'target' => $this->mTitle->getPrefixedDbkey(),
3507 'ids' => $oldid
3508 );
3509 $cdel = $sk->revDeleteLink( $query, $revision->isDeleted( File::DELETED_RESTRICTED ), $canHide );
3510 }
3511 $cdel .= ' ';
3512 }
3513
3514 # Show user links if allowed to see them. If hidden, then show them only if requested...
3515 $userlinks = $sk->revUserTools( $revision, !$unhide );
3516
3517 $m = wfMsg( 'revision-info-current' );
3518 $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
3519 ? 'revision-info-current'
3520 : 'revision-info';
3521
3522 $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" .
3523 wfMsgExt(
3524 $infomsg,
3525 array( 'parseinline', 'replaceafter' ),
3526 $td,
3527 $userlinks,
3528 $revision->getID(),
3529 $tddate,
3530 $tdtime,
3531 $revision->getUser()
3532 ) .
3533 "</div>\n" .
3534 "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
3535 $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
3536 $wgOut->setSubtitle( $r );
3537 }
3538
3539 /**
3540 * This function is called right before saving the wikitext,
3541 * so we can do things like signatures and links-in-context.
3542 *
3543 * @param $text String
3544 */
3545 public function preSaveTransform( $text ) {
3546 global $wgParser, $wgUser;
3547 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
3548 }
3549
3550 /* Caching functions */
3551
3552 /**
3553 * checkLastModified returns true if it has taken care of all
3554 * output to the client that is necessary for this request.
3555 * (that is, it has sent a cached version of the page)
3556 */
3557 protected function tryFileCache() {
3558 static $called = false;
3559 if ( $called ) {
3560 wfDebug( "Article::tryFileCache(): called twice!?\n" );
3561 return false;
3562 }
3563 $called = true;
3564 if ( $this->isFileCacheable() ) {
3565 $cache = new HTMLFileCache( $this->mTitle );
3566 if ( $cache->isFileCacheGood( $this->mTouched ) ) {
3567 wfDebug( "Article::tryFileCache(): about to load file\n" );
3568 $cache->loadFromFileCache();
3569 return true;
3570 } else {
3571 wfDebug( "Article::tryFileCache(): starting buffer\n" );
3572 ob_start( array( &$cache, 'saveToFileCache' ) );
3573 }
3574 } else {
3575 wfDebug( "Article::tryFileCache(): not cacheable\n" );
3576 }
3577 return false;
3578 }
3579
3580 /**
3581 * Check if the page can be cached
3582 * @return bool
3583 */
3584 public function isFileCacheable() {
3585 $cacheable = false;
3586 if ( HTMLFileCache::useFileCache() ) {
3587 $cacheable = $this->getID() && !$this->mRedirectedFrom;
3588 // Extension may have reason to disable file caching on some pages.
3589 if ( $cacheable ) {
3590 $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
3591 }
3592 }
3593 return $cacheable;
3594 }
3595
3596 /**
3597 * Loads page_touched and returns a value indicating if it should be used
3598 *
3599 */
3600 public function checkTouched() {
3601 if ( !$this->mDataLoaded ) {
3602 $this->loadPageData();
3603 }
3604 return !$this->mIsRedirect;
3605 }
3606
3607 /**
3608 * Get the page_touched field
3609 */
3610 public function getTouched() {
3611 # Ensure that page data has been loaded
3612 if ( !$this->mDataLoaded ) {
3613 $this->loadPageData();
3614 }
3615 return $this->mTouched;
3616 }
3617
3618 /**
3619 * Get the page_latest field
3620 */
3621 public function getLatest() {
3622 if ( !$this->mDataLoaded ) {
3623 $this->loadPageData();
3624 }
3625 return (int)$this->mLatest;
3626 }
3627
3628 /**
3629 * Edit an article without doing all that other stuff
3630 * The article must already exist; link tables etc
3631 * are not updated, caches are not flushed.
3632 *
3633 * @param $text String: text submitted
3634 * @param $comment String: comment submitted
3635 * @param $minor Boolean: whereas it's a minor modification
3636 */
3637 public function quickEdit( $text, $comment = '', $minor = 0 ) {
3638 wfProfileIn( __METHOD__ );
3639
3640 $dbw = wfGetDB( DB_MASTER );
3641 $revision = new Revision( array(
3642 'page' => $this->getId(),
3643 'text' => $text,
3644 'comment' => $comment,
3645 'minor_edit' => $minor ? 1 : 0,
3646 ) );
3647 $revision->insertOn( $dbw );
3648 $this->updateRevisionOn( $dbw, $revision );
3649
3650 wfRunHooks( 'NewRevisionFromEditComplete', array( $this, $revision, false, $wgUser ) );
3651
3652 wfProfileOut( __METHOD__ );
3653 }
3654
3655 /**
3656 * Used to increment the view counter
3657 *
3658 * @param $id Integer: article id
3659 */
3660 public static function incViewCount( $id ) {
3661 $id = intval( $id );
3662 global $wgHitcounterUpdateFreq;
3663
3664 $dbw = wfGetDB( DB_MASTER );
3665 $pageTable = $dbw->tableName( 'page' );
3666 $hitcounterTable = $dbw->tableName( 'hitcounter' );
3667 $acchitsTable = $dbw->tableName( 'acchits' );
3668
3669 if ( $wgHitcounterUpdateFreq <= 1 ) {
3670 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
3671 return;
3672 }
3673
3674 # Not important enough to warrant an error page in case of failure
3675 $oldignore = $dbw->ignoreErrors( true );
3676
3677 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
3678
3679 $checkfreq = intval( $wgHitcounterUpdateFreq / 25 + 1 );
3680 if ( ( rand() % $checkfreq != 0 ) or ( $dbw->lastErrno() != 0 ) ) {
3681 # Most of the time (or on SQL errors), skip row count check
3682 $dbw->ignoreErrors( $oldignore );
3683 return;
3684 }
3685
3686 $res = $dbw->query( "SELECT COUNT(*) as n FROM $hitcounterTable" );
3687 $row = $dbw->fetchObject( $res );
3688 $rown = intval( $row->n );
3689 if ( $rown >= $wgHitcounterUpdateFreq ) {
3690 wfProfileIn( 'Article::incViewCount-collect' );
3691 $old_user_abort = ignore_user_abort( true );
3692
3693 $dbType = $dbw->getType();
3694 $dbw->lockTables( array(), array( 'hitcounter' ), __METHOD__, false );
3695 $tabletype = $dbType == 'mysql' ? "ENGINE=HEAP " : '';
3696 $dbw->query( "CREATE TEMPORARY TABLE $acchitsTable $tabletype AS " .
3697 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable " .
3698 'GROUP BY hc_id', __METHOD__ );
3699 $dbw->delete( 'hitcounter', '*', __METHOD__ );
3700 $dbw->unlockTables( __METHOD__ );
3701 if ( $dbType == 'mysql' ) {
3702 $dbw->query( "UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n " .
3703 'WHERE page_id = hc_id', __METHOD__ );
3704 }
3705 else {
3706 $dbw->query( "UPDATE $pageTable SET page_counter=page_counter + hc_n " .
3707 "FROM $acchitsTable WHERE page_id = hc_id", __METHOD__ );
3708 }
3709 $dbw->query( "DROP TABLE $acchitsTable", __METHOD__ );
3710
3711 ignore_user_abort( $old_user_abort );
3712 wfProfileOut( 'Article::incViewCount-collect' );
3713 }
3714 $dbw->ignoreErrors( $oldignore );
3715 }
3716
3717 /**#@+
3718 * The onArticle*() functions are supposed to be a kind of hooks
3719 * which should be called whenever any of the specified actions
3720 * are done.
3721 *
3722 * This is a good place to put code to clear caches, for instance.
3723 *
3724 * This is called on page move and undelete, as well as edit
3725 *
3726 * @param $title a title object
3727 */
3728 public static function onArticleCreate( $title ) {
3729 # Update existence markers on article/talk tabs...
3730 if ( $title->isTalkPage() ) {
3731 $other = $title->getSubjectPage();
3732 } else {
3733 $other = $title->getTalkPage();
3734 }
3735 $other->invalidateCache();
3736 $other->purgeSquid();
3737
3738 $title->touchLinks();
3739 $title->purgeSquid();
3740 $title->deleteTitleProtection();
3741 }
3742
3743 public static function onArticleDelete( $title ) {
3744 global $wgMessageCache;
3745 # Update existence markers on article/talk tabs...
3746 if ( $title->isTalkPage() ) {
3747 $other = $title->getSubjectPage();
3748 } else {
3749 $other = $title->getTalkPage();
3750 }
3751 $other->invalidateCache();
3752 $other->purgeSquid();
3753
3754 $title->touchLinks();
3755 $title->purgeSquid();
3756
3757 # File cache
3758 HTMLFileCache::clearFileCache( $title );
3759
3760 # Messages
3761 if ( $title->getNamespace() == NS_MEDIAWIKI ) {
3762 $wgMessageCache->replace( $title->getDBkey(), false );
3763 }
3764 # Images
3765 if ( $title->getNamespace() == NS_FILE ) {
3766 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
3767 $update->doUpdate();
3768 }
3769 # User talk pages
3770 if ( $title->getNamespace() == NS_USER_TALK ) {
3771 $user = User::newFromName( $title->getText(), false );
3772 $user->setNewtalk( false );
3773 }
3774 # Image redirects
3775 RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
3776 }
3777
3778 /**
3779 * Purge caches on page update etc
3780 */
3781 public static function onArticleEdit( $title, $flags = '' ) {
3782 global $wgDeferredUpdateList;
3783
3784 // Invalidate caches of articles which include this page
3785 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
3786
3787 // Invalidate the caches of all pages which redirect here
3788 $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
3789
3790 # Purge squid for this page only
3791 $title->purgeSquid();
3792
3793 # Clear file cache for this page only
3794 HTMLFileCache::clearFileCache( $title );
3795 }
3796
3797 /**#@-*/
3798
3799 /**
3800 * Overriden by ImagePage class, only present here to avoid a fatal error
3801 * Called for ?action=revert
3802 */
3803 public function revert() {
3804 global $wgOut;
3805 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3806 }
3807
3808 /**
3809 * Info about this page
3810 * Called for ?action=info when $wgAllowPageInfo is on.
3811 */
3812 public function info() {
3813 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
3814
3815 if ( !$wgAllowPageInfo ) {
3816 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
3817 return;
3818 }
3819
3820 $page = $this->mTitle->getSubjectPage();
3821
3822 $wgOut->setPagetitle( $page->getPrefixedText() );
3823 $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
3824 $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
3825
3826 if ( !$this->mTitle->exists() ) {
3827 $wgOut->addHTML( '<div class="noarticletext">' );
3828 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
3829 // This doesn't quite make sense; the user is asking for
3830 // information about the _page_, not the message... -- RC
3831 $wgOut->addHTML( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
3832 } else {
3833 $msg = $wgUser->isLoggedIn()
3834 ? 'noarticletext'
3835 : 'noarticletextanon';
3836 $wgOut->addHTML( wfMsgExt( $msg, 'parse' ) );
3837 }
3838 $wgOut->addHTML( '</div>' );
3839 } else {
3840 $dbr = wfGetDB( DB_SLAVE );
3841 $wl_clause = array(
3842 'wl_title' => $page->getDBkey(),
3843 'wl_namespace' => $page->getNamespace() );
3844 $numwatchers = $dbr->selectField(
3845 'watchlist',
3846 'COUNT(*)',
3847 $wl_clause,
3848 __METHOD__,
3849 $this->getSelectOptions() );
3850
3851 $pageInfo = $this->pageCountInfo( $page );
3852 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
3853
3854 $wgOut->addHTML( "<ul><li>" . wfMsg( "numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
3855 $wgOut->addHTML( "<li>" . wfMsg( 'numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>' );
3856 if ( $talkInfo ) {
3857 $wgOut->addHTML( '<li>' . wfMsg( "numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>' );
3858 }
3859 $wgOut->addHTML( '<li>' . wfMsg( "numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
3860 if ( $talkInfo ) {
3861 $wgOut->addHTML( '<li>' . wfMsg( 'numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
3862 }
3863 $wgOut->addHTML( '</ul>' );
3864 }
3865 }
3866
3867 /**
3868 * Return the total number of edits and number of unique editors
3869 * on a given page. If page does not exist, returns false.
3870 *
3871 * @param $title Title object
3872 * @return array
3873 */
3874 public function pageCountInfo( $title ) {
3875 $id = $title->getArticleId();
3876 if ( $id == 0 ) {
3877 return false;
3878 }
3879 $dbr = wfGetDB( DB_SLAVE );
3880 $rev_clause = array( 'rev_page' => $id );
3881 $edits = $dbr->selectField(
3882 'revision',
3883 'COUNT(rev_page)',
3884 $rev_clause,
3885 __METHOD__,
3886 $this->getSelectOptions()
3887 );
3888 $authors = $dbr->selectField(
3889 'revision',
3890 'COUNT(DISTINCT rev_user_text)',
3891 $rev_clause,
3892 __METHOD__,
3893 $this->getSelectOptions()
3894 );
3895 return array( 'edits' => $edits, 'authors' => $authors );
3896 }
3897
3898 /**
3899 * Return a list of templates used by this article.
3900 * Uses the templatelinks table
3901 *
3902 * @return Array of Title objects
3903 */
3904 public function getUsedTemplates() {
3905 $result = array();
3906 $id = $this->mTitle->getArticleID();
3907 if ( $id == 0 ) {
3908 return array();
3909 }
3910 $dbr = wfGetDB( DB_SLAVE );
3911 $res = $dbr->select( array( 'templatelinks' ),
3912 array( 'tl_namespace', 'tl_title' ),
3913 array( 'tl_from' => $id ),
3914 __METHOD__ );
3915 if ( $res !== false ) {
3916 foreach ( $res as $row ) {
3917 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
3918 }
3919 }
3920 $dbr->freeResult( $res );
3921 return $result;
3922 }
3923
3924 /**
3925 * Returns a list of hidden categories this page is a member of.
3926 * Uses the page_props and categorylinks tables.
3927 *
3928 * @return Array of Title objects
3929 */
3930 public function getHiddenCategories() {
3931 $result = array();
3932 $id = $this->mTitle->getArticleID();
3933 if ( $id == 0 ) {
3934 return array();
3935 }
3936 $dbr = wfGetDB( DB_SLAVE );
3937 $res = $dbr->select( array( 'categorylinks', 'page_props', 'page' ),
3938 array( 'cl_to' ),
3939 array( 'cl_from' => $id, 'pp_page=page_id', 'pp_propname' => 'hiddencat',
3940 'page_namespace' => NS_CATEGORY, 'page_title=cl_to' ),
3941 __METHOD__ );
3942 if ( $res !== false ) {
3943 foreach ( $res as $row ) {
3944 $result[] = Title::makeTitle( NS_CATEGORY, $row->cl_to );
3945 }
3946 }
3947 $dbr->freeResult( $res );
3948 return $result;
3949 }
3950
3951 /**
3952 * Return an applicable autosummary if one exists for the given edit.
3953 * @param $oldtext String: the previous text of the page.
3954 * @param $newtext String: The submitted text of the page.
3955 * @param $flags Bitmask: a bitmask of flags submitted for the edit.
3956 * @return string An appropriate autosummary, or an empty string.
3957 */
3958 public static function getAutosummary( $oldtext, $newtext, $flags ) {
3959 # Decide what kind of autosummary is needed.
3960
3961 # Redirect autosummaries
3962 $ot = Title::newFromRedirect( $oldtext );
3963 $rt = Title::newFromRedirect( $newtext );
3964 if ( is_object( $rt ) && ( !is_object( $ot ) || !$rt->equals( $ot ) || $ot->getFragment() != $rt->getFragment() ) ) {
3965 return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
3966 }
3967
3968 # New page autosummaries
3969 if ( $flags & EDIT_NEW && strlen( $newtext ) ) {
3970 # If they're making a new article, give its text, truncated, in the summary.
3971 global $wgContLang;
3972 $truncatedtext = $wgContLang->truncate(
3973 str_replace( "\n", ' ', $newtext ),
3974 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
3975 return wfMsgForContent( 'autosumm-new', $truncatedtext );
3976 }
3977
3978 # Blanking autosummaries
3979 if ( $oldtext != '' && $newtext == '' ) {
3980 return wfMsgForContent( 'autosumm-blank' );
3981 } elseif ( strlen( $oldtext ) > 10 * strlen( $newtext ) && strlen( $newtext ) < 500 ) {
3982 # Removing more than 90% of the article
3983 global $wgContLang;
3984 $truncatedtext = $wgContLang->truncate(
3985 $newtext,
3986 max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
3987 return wfMsgForContent( 'autosumm-replace', $truncatedtext );
3988 }
3989
3990 # If we reach this point, there's no applicable autosummary for our case, so our
3991 # autosummary is empty.
3992 return '';
3993 }
3994
3995 /**
3996 * Add the primary page-view wikitext to the output buffer
3997 * Saves the text into the parser cache if possible.
3998 * Updates templatelinks if it is out of date.
3999 *
4000 * @param $text String
4001 * @param $cache Boolean
4002 */
4003 public function outputWikiText( $text, $cache = true, $parserOptions = false ) {
4004 global $wgOut;
4005
4006 $this->mParserOutput = $this->getOutputFromWikitext( $text, $cache, $parserOptions );
4007 $wgOut->addParserOutput( $this->mParserOutput );
4008 }
4009
4010 /**
4011 * This does all the heavy lifting for outputWikitext, except it returns the parser
4012 * output instead of sending it straight to $wgOut. Makes things nice and simple for,
4013 * say, embedding thread pages within a discussion system (LiquidThreads)
4014 */
4015 public function getOutputFromWikitext( $text, $cache = true, $parserOptions = false ) {
4016 global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
4017
4018 if ( !$parserOptions ) {
4019 $parserOptions = $this->getParserOptions();
4020 }
4021
4022 $time = - wfTime();
4023 $this->mParserOutput = $wgParser->parse( $text, $this->mTitle,
4024 $parserOptions, true, true, $this->getRevIdFetched() );
4025 $time += wfTime();
4026
4027 # Timing hack
4028 if ( $time > 3 ) {
4029 wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
4030 $this->mTitle->getPrefixedDBkey() ) );
4031 }
4032
4033 if ( $wgEnableParserCache && $cache && $this && $this->mParserOutput->getCacheTime() != -1 ) {
4034 $parserCache = ParserCache::singleton();
4035 $parserCache->save( $this->mParserOutput, $this, $parserOptions );
4036 }
4037 // Make sure file cache is not used on uncacheable content.
4038 // Output that has magic words in it can still use the parser cache
4039 // (if enabled), though it will generally expire sooner.
4040 if ( $this->mParserOutput->getCacheTime() == -1 || $this->mParserOutput->containsOldMagic() ) {
4041 $wgUseFileCache = false;
4042 }
4043 $this->doCascadeProtectionUpdates( $this->mParserOutput );
4044 return $this->mParserOutput;
4045 }
4046
4047 /**
4048 * Get parser options suitable for rendering the primary article wikitext
4049 */
4050 public function getParserOptions() {
4051 global $wgUser;
4052 if ( !$this->mParserOptions ) {
4053 $this->mParserOptions = new ParserOptions( $wgUser );
4054 $this->mParserOptions->setTidy( true );
4055 $this->mParserOptions->enableLimitReport();
4056 }
4057 return $this->mParserOptions;
4058 }
4059
4060 protected function doCascadeProtectionUpdates( $parserOutput ) {
4061 if ( !$this->isCurrent() || wfReadOnly() || !$this->mTitle->areRestrictionsCascading() ) {
4062 return;
4063 }
4064
4065 // templatelinks table may have become out of sync,
4066 // especially if using variable-based transclusions.
4067 // For paranoia, check if things have changed and if
4068 // so apply updates to the database. This will ensure
4069 // that cascaded protections apply as soon as the changes
4070 // are visible.
4071
4072 # Get templates from templatelinks
4073 $id = $this->mTitle->getArticleID();
4074
4075 $tlTemplates = array();
4076
4077 $dbr = wfGetDB( DB_SLAVE );
4078 $res = $dbr->select( array( 'templatelinks' ),
4079 array( 'tl_namespace', 'tl_title' ),
4080 array( 'tl_from' => $id ),
4081 __METHOD__ );
4082
4083 global $wgContLang;
4084 foreach ( $res as $row ) {
4085 $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
4086 }
4087
4088 # Get templates from parser output.
4089 $poTemplates = array();
4090 foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
4091 foreach ( $templates as $dbk => $id ) {
4092 $poTemplates["$ns:$dbk"] = true;
4093 }
4094 }
4095
4096 # Get the diff
4097 # Note that we simulate array_diff_key in PHP <5.0.x
4098 $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
4099
4100 if ( count( $templates_diff ) > 0 ) {
4101 # Whee, link updates time.
4102 $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
4103 $u->doUpdate();
4104 }
4105 }
4106
4107 /**
4108 * Update all the appropriate counts in the category table, given that
4109 * we've added the categories $added and deleted the categories $deleted.
4110 *
4111 * @param $added array The names of categories that were added
4112 * @param $deleted array The names of categories that were deleted
4113 * @return null
4114 */
4115 public function updateCategoryCounts( $added, $deleted ) {
4116 $ns = $this->mTitle->getNamespace();
4117 $dbw = wfGetDB( DB_MASTER );
4118
4119 # First make sure the rows exist. If one of the "deleted" ones didn't
4120 # exist, we might legitimately not create it, but it's simpler to just
4121 # create it and then give it a negative value, since the value is bogus
4122 # anyway.
4123 #
4124 # Sometimes I wish we had INSERT ... ON DUPLICATE KEY UPDATE.
4125 $insertCats = array_merge( $added, $deleted );
4126 if ( !$insertCats ) {
4127 # Okay, nothing to do
4128 return;
4129 }
4130 $insertRows = array();
4131 foreach ( $insertCats as $cat ) {
4132 $insertRows[] = array(
4133 'cat_id' => $dbw->nextSequenceValue( 'category_cat_id_seq' ),
4134 'cat_title' => $cat
4135 );
4136 }
4137 $dbw->insert( 'category', $insertRows, __METHOD__, 'IGNORE' );
4138
4139 $addFields = array( 'cat_pages = cat_pages + 1' );
4140 $removeFields = array( 'cat_pages = cat_pages - 1' );
4141 if ( $ns == NS_CATEGORY ) {
4142 $addFields[] = 'cat_subcats = cat_subcats + 1';
4143 $removeFields[] = 'cat_subcats = cat_subcats - 1';
4144 } elseif ( $ns == NS_FILE ) {
4145 $addFields[] = 'cat_files = cat_files + 1';
4146 $removeFields[] = 'cat_files = cat_files - 1';
4147 }
4148
4149 if ( $added ) {
4150 $dbw->update(
4151 'category',
4152 $addFields,
4153 array( 'cat_title' => $added ),
4154 __METHOD__
4155 );
4156 }
4157 if ( $deleted ) {
4158 $dbw->update(
4159 'category',
4160 $removeFields,
4161 array( 'cat_title' => $deleted ),
4162 __METHOD__
4163 );
4164 }
4165 }
4166
4167 /** Lightweight method to get the parser output for a page, checking the parser cache
4168 * and so on. Doesn't consider most of the stuff that Article::view is forced to
4169 * consider, so it's not appropriate to use there.
4170 */
4171 function getParserOutput( $oldid = null ) {
4172 global $wgEnableParserCache, $wgUser, $wgOut;
4173
4174 // Should the parser cache be used?
4175 $useParserCache = $wgEnableParserCache &&
4176 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
4177 $this->exists() &&
4178 $oldid === null;
4179
4180 wfDebug( __METHOD__ . ': using parser cache: ' . ( $useParserCache ? 'yes' : 'no' ) . "\n" );
4181 if ( $wgUser->getOption( 'stubthreshold' ) ) {
4182 wfIncrStats( 'pcache_miss_stub' );
4183 }
4184
4185 $parserOutput = false;
4186 if ( $useParserCache ) {
4187 $parserOutput = ParserCache::singleton()->get( $this, $this->getParserOptions() );
4188 }
4189
4190 if ( $parserOutput === false ) {
4191 // Cache miss; parse and output it.
4192 $rev = Revision::newFromTitle( $this->getTitle(), $oldid );
4193
4194 return $this->getOutputFromWikitext( $rev->getText(), $useParserCache );
4195 } else {
4196 return $parserOutput;
4197 }
4198 }
4199 }